Skip to content

Instantly share code, notes, and snippets.

@chuckg
Forked from hartmantis/spec_helper.rb
Last active October 19, 2017 07:33
Show Gist options
  • Save chuckg/7dac42065a1c08d93248 to your computer and use it in GitHub Desktop.
Save chuckg/7dac42065a1c08d93248 to your computer and use it in GitHub Desktop.
ChefSpec/RSpec 3 stubs for testing a recipe in isolation
# Updated for rspec 3.0:
module IncludeRecipeHelper
def enable_stubbed_include_recipe
# Don't worry about external cookbook dependencies
allow_any_instance_of(Chef::Cookbook::Metadata).to receive(:depends)
# Test each recipe in isolation, regardless of includes
@included_recipes = []
allow_any_instance_of(Chef::RunContext).to receive(:loaded_recipe?).and_return(false)
allow_any_instance_of(Chef::Recipe).to receive(:include_recipe) do |recipe, included_recipe|
allow_any_instance_of(Chef::RunContext).to receive(:loaded_recipe?).with(included_recipe).and_return(true)
@included_recipes << included_recipe
end
allow_any_instance_of(Chef::RunContext).to receive(:loaded_recipes).and_return(@included_recipes)
end
end

Place include_recipe_helper.rb in spec/support/helpers/ directory.

Then create a spec/spec_helper.rb with the following:

require 'chefspec'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir["./spec/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|
  # ...
  config.include IncludeRecipeHelper
end

Example usage, assuming example::default includes other_cookbook::recipe:

require_relative '../spec_helper'

describe 'example::default' do
  let(:runner) { ChefSpec::Runner.new } 
  subject { runner.converge(described_recipe) }

  before do
    enable_stubbed_include_recipe
  end

  it { should include_recipe('other_cookbook::recipe') }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment