Let's suppose that we have the following coookbook -
recipes/server.rb:
package 'apache2'
template '/var/www/html/index.html' do
source 'index.html.erb'
variables(:name => "Dmitri")
end
service 'apache2' do
action [:enable, :start ]
subscribes :restart, 'template[/var/www/html/index.html]', :immediately
end
Unit testing is executed from these files - require 'chefspec'
require 'chefspec/berkshelf'
ChefSpec::Coverage.start!
spec/unit/recipes/default_spec.rb:
require 'spec_helper'
describe 'apache::default' do
context 'When all attributes are default, on an unspecified platform' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new({:platform => 'centos', :version => '7.0'})
runner.converge(described_recipe)
end
it 'installs the correct package' do
expect(chef_run).to install_package('apache2')
end
it 'creates an default html file' do
expect(chef_run).to create_template('/var/www/html/index.html')
end
it 'starts the service' do
expect(chef_run).to start_service('apache2')
end
it 'starts the service' do
expect(chef_run).to enable_service('apache2')
end
end
end
Execute the tests in following way:
chef exec rspec spec/unit/recipes/default_spec.rb
Example output:
....
Finished in 0.37569 seconds (files took 0.97682 seconds to load)
4 examples, 0 failures
ChefSpec Coverage report generated...
Total Resources: 3
Touched Resources: 3
Touch Coverage: 100.0%
You are awesome and so is your test coverage! Have a fantastic day!