Help us understand the problem. What is going on with this article?

chefspec で libraries で定義した mixin のテストをする

More than 5 years have passed since last update.

こんな libraries を書いたとする

libraries/awesome_mixin.rb
module Awesome
  module Mixin
    def foo
      node['foo']
    end
  end
end

Chef::Recipe.send(:include, Awesome::Mixin)
Chef::Resource.send(:include, Awesome::Mixin)

node なんかを使っていなければchefspecでlibraries内のメソッドをテストするのやり方で十分なのだが、node を使っている場合は次のようにする

spec/spec_helper.rb
require 'chefspec'

def cookbook_root
  File.expand_path("../..", __FILE__)
end

def cookbook_name
  'mycookbook'
end
spec/libraries/awesome_mixin_spec.rb
require_relative '../spec_helper'
require_relative '../../libraries/awesome_mixin'

describe Awesome::Mixin do
  let(:cookbook_collection) do
    cookbook_version = Chef::CookbookVersion.new(cookbook_name, cookbook_root)
    cookbook_versions = { cookbook_name => cookbook_version }
    Chef::CookbookCollection.new(cookbook_versions)
  end

  let(:events) do
    Chef::EventDispatch::Dispatcher.new
  end

  let(:node) do
    Chef::Node.new.tap {|node|
      node.set['foo'] = 'yay!'
    }
  end

  let(:run_context) do
    run_context = Chef::RunContext.new(node, cookbook_collection, events)
  end

  let(:recipe) do
    Chef::Recipe.new(cookbook_name, "test", run_context)
  end

  it do
    expect(recipe.foo).to eql('yay!')
  end
end

長い!!

sonots
A Ruby, Fluentd, and Chainer Committer. SRE Engineer. Qiitaは小ネタの投稿場所として利用しています。業務コードで、なぜそういう書き方をしているのか解説をQiitaに書いて、コードにはQiitaへのリンクを張る、という使い方をしていることが多いです(自己紹介じゃない)
https://medium.com/@sonots
zozotech
70億人のファッションを技術の力で変えていく
https://tech.zozo.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away