Skip to content

Instantly share code, notes, and snippets.

@hartmantis
Last active November 15, 2017 15:50
Show Gist options
  • Save hartmantis/5505152 to your computer and use it in GitHub Desktop.
Save hartmantis/5505152 to your computer and use it in GitHub Desktop.
ChefSpec stubs for testing a recipe in isolation
require 'chefspec'
module SpecHelper
def global_stubs
# Don't worry about external cookbook dependencies
Chef::Cookbook::Metadata.any_instance.stub(:depends)
# Test each recipe in isolation, regardless of includes
@included_recipes = []
Chef::RunContext.any_instance.stub(:loaded_recipe?).and_return(false)
Chef::Recipe.any_instance.stub(:include_recipe) do |i|
Chef::RunContext.any_instance.stub(:loaded_recipe?).with(i).and_return(true)
@included_recipes << i
end
Chef::RunContext.any_instance.stub(:loaded_recipes).and_return(@included_recipes)
end
end
@juliancooper
Copy link

This is very handy.

Just adding one observation, it seems like if your recipe is using LWRPs defined in another cookbook, stubbing out "depends" will cause the ChefSpec::Runner to be unable to find them, commenting out that stub might be advisable depending on what level of isolation you're looking for.

@atheiman
Copy link

I dont know if I was doing something wrong, or something with the api has changed (this is from 2013), but this didnt work for me. Though it did get me on the road to this solution if you want to ensure include_recipe is called with the right recipe(s), but don't want to load the resources in the included recipe(s):

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

it 'includes the correct recipes' do
  chef_run
  expect(@included_recipes).to match_array(@stubbed_recipes)
end

A complete example of this: atheiman/test-cookbook#4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment