In my last post, MVT: Foodcritic and Travis CI I described the process for having Travis CI look after your cookbooks and run Foodcritic, the cookbook lint tool, on your cookbook after each git push. In this post, we’ll iterate on the “Minimum Viable Test” idea by adding in support for knife’s cookbook testing.
Wait, I’m already running foodcritic, do I really need to run knife cookbook test, too?
I’ll use a very simple example to demonstrate that you do.
Let’s create a very basic cookbook:
1234
knife cookbook create very_basic
** Creating cookbook very_basic
** Creating README for cookbook: very_basic
** Creating metadata for cookbook: very_basic
Next, we’ll write a flawed recipe:
cookbooks/very_basic/recipes/default.rb
1234
package"flawed"doaction:nothingendend
Now, run foodcritic on this cookbook:
1
foodcritic cookbooks/very_basic
Foodcritic doesn’t throw any errors or find any problem with the cookbook.
Let’s try testing it with knife:
123456
knife cookbook test very_basic
checking very_basic
Running syntax check on very_basic
Validating ruby files
FATAL: Cookbook file recipes/default.rb has a ruby syntax error:
FATAL: /Users/nharvey/projects/chef-hosted/.chef/../cookbooks/very_basic/recipes/default.rb:22: syntax error, unexpected keyword_end, expecting $end
OK, it should now be obvious that knife cookbook test should be included as part of our MVT.
To get Travis CI running knife cookbook test for us, we’ll need to add or update the following files:
.travis.yml
Rakefile
test/.chef/knife.rb
test/support/Gemfile
Of course, this assumes you’ve configured your cookbook as described in the previous post. Let’s start with the Rakefile.
In the file snippet above, I’ve only included the parts that are relevant for getting knife working. I’ll include the full source of the Rakefile at the end of the article.
Next, let’s add this rake task to our .travis.yml file.
And, of course, we’ll need to add Chef to our Gemfile. Be sure to specify a modern version as Travis CI will use 0.8.10 by default (at the time of this writing).
That’s it. On your next git push Travis CI should run knife cookbook test on your cookbook.
Running locally
To run the rake tasks locally, you’ll need to tell bundler where the Gemfile is, or you’ll need to move it to the root directory of your cookbook and update .travis.yml appropriately. Use the following command to run your tests locally: