unit-testingrspecchef-infrachefspec

Chefspec: does chefspec load all the recipes, libraries, custom resources etc all initially


In my cookbook(its a legacy code), I have around 20+ recipes, around 15 modules in libraries directory, some custom resources.

I am trying to add chefspecs for recipes, I have created package_spec.rb spec file for recipe package (I am using chef12, so I have a policyfile, for which I have added an entry in spec_helper.rb). and the in the recipe, I have a simple code

package'monit' do
  action :install
end

Similaraly the spec file contains a small test as:

it 'installs monit' do
  expect(chef_run).to install_package('monit')
end

But when I am trying to run the spec file as:

chef rspec <spec_file_path>

It is throwing some errors for methods in libraries, custom resources etc.

So I have 2 points:

  1. Does the chefspec load all the recipes, libraries, custom resources etc initially everytime, even for running test for a single recipe?
  2. If yes, how can we make it load only those recipe/files which are related to that recipe?

Thanks !!


Solution

  • It is actually not ChefSpec, but Chef itself. All ChefSpec does is rewrite the resource action methods, so that they do nothing except write somewhere down, that the action was called.

    ChefSpec calls chef-client's converge and it is Chef itself who loads libraries, attributes and recipes from the cookbook. And, sorry, you can't change this behaviour, Chef loads the cookbook as a whole, even if you need just 1 small recipe from it.