Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active November 21, 2017 15:42
Show Gist options
  • Save atheiman/cbeb79f58cc959947b6f38d1301b5a41 to your computer and use it in GitHub Desktop.
Save atheiman/cbeb79f58cc959947b6f38d1301b5a41 to your computer and use it in GitHub Desktop.
Stubbing `include_recipe` while ensuring correct recipes are included. complete example: https://github.com/atheiman/test-cookbook/pull/4
# test_cookbook/recipes/default.rb
include_recipe 'test_cookbook::included_recipe'
include_recipe 'apt'
# test_cookbook/spec/recipes/default_spec.rb
describe 'test_cookbook::default' do
before(:all) { @included_recipes = [] }
before do
@stubbed_recipes = %w[test_cookbook::included_recipe apt]
@stubbed_recipes.each do |r|
allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).with(r) do
@included_recipes << r
end
end
end
cached(:chef_run) { ChefSpec::ServerRunner.new.converge(described_recipe) }
it 'includes the correct recipes' do
chef_run
expect(@included_recipes).to match_array(@stubbed_recipes)
end
end
# as a shared example
shared_examples 'includes recipes' do |*recipes|
before(:all) { @included_recipes = [] }
before do
@stubbed_recipes = Array(recipes).flatten
@stubbed_recipes.each do |r|
allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).with(r) do
@included_recipes << r
end
end
end
it 'includes the correct recipes' do
chef_run
expect(@included_recipes).to eq(@stubbed_recipes)
end
end
# some_recipe_spec.rb
describe 'some_cookbook::some_recipe' do
cached(:chef_run) { ChefSpec::ServerRunner.new.converge(described_recipe) }
include_examples 'includes recipes', ['some_cookbook::included_recipe']
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment