Chef - Testing Cookbooks


Advertisements

In case the cookbook is directly deployed and run on the production server, there are high chances that the cookbook can break up in production. The best way to prevent this from happening is, testing the cookbook in the setup environment.

Following are the steps for testing.

Step 1 − Install the cookbook using the following command.

vipin@laptop:~/chef-repo $ knife cookbook site install <cookbook name> 

Step 2 − Run the knife cookbook test commands on the working cookbook.

vipin@laptop:~/chef-repo $ knife cookbook test VTest  
checking ntp 
Running syntax check on ntp 
Validating ruby files 
Validating templates

Step 3 − Break something in the cookbook and test again.

vipin@laptop:~/chef-repo $ subl cookbooks/VTest/recipes/default.rb 
... 
[ node['ntp']['varlibdir'] 
node['ntp']['statsdir'] ].each do |ntpdir| 
   directory ntpdir do 
      owner node['ntp']['var_owner'] 
      group node['ntp']['var_group'] 
      mode 0755 
   end 
end

Step 4 − Run the knife test command again.

vipin@laptop:~/chef-repo $ knife cookbook test ntp 
checking ntp 
Running syntax check on ntp 
Validating ruby files 
FATAL: Cookbook file recipes/default.rb has a ruby syntax error: 
FATAL: cookbooks/ntp/recipes/default.rb:25: syntax error, 
unexpected tIDENTIFIER, expecting ']' 
FATAL: node['ntp']['statsdir'] ].each do |ntpdir| 
FATAL: ^ 
FATAL: cookbooks/ntp/recipes/default.rb:25: syntax error, 
unexpected ']', expecting $end 
FATAL: node['ntp']['statsdir'] ].each do |ntpdir| 
FATAL: 

Working Method

Knife cookbook test executes a Ruby syntax check on all the Ruby files within the cookbook as well as all ERB templates. It loops through Ruby files and runs Ruby –c against each of them. Ruby –c checks the syntax of the script and quits without running it.

After going through all the Ruby files, knife cookbook test goes through all ERB templates and pipes, the redundant version created by –x through Ruby –c.

Limitations

Knife cookbook test does only a simple syntax check on the Ruby files and ERB templates. We can go ahead fully test driven by using ChefSpec and test kitchen.

Advertisements