LoginSignup
3
3

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-02-10

こんな 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

長い!!

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3