こんな 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
長い!!