The Puppet Development Kit doesn’t just set us up to create well-written modules—it also lets us write unit tests for our modules and ensure the changes we expect are being made when we run our Puppet code. This is done through the use of RSpec, a Ruby-based testing framework, and the `rspec-puppet` and `rspec-puppet-facts` plugins. RSpec uses behavior-driven development concepts to check the end state of our code. These tests are written in a human-readable language based on Ruby.
By writing unit tests for our modules, we can ensure we’re putting forth the highest-quality modules and prevent any unexpected production issues. Unit tests essentially work as another layer of protection against poor code, typos, and all the other gremlins that can end up in our modules.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Test That the Required Classes Are Contained
Change to the
spec
directory of thenginx
module:cd /etc/puppetlabs/code/environments/production/modules/nginx/spec/
Open the
classes/nginx_spec.rb
file:sudo vim classes/nginx_spec.rb
Review the existing test. Currently, it is set up to check if the module will compile.
Add unit tests to ensure the desired classes are contained:
describe ‘nginx’ do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }it { is_expected.to contain_class('nginx::install') } it { is_expected.to contain_class('nginx::config') } it { is_expected.to contain_class('nginx::service') } it { is_expected.to compile } end end
end
- Test That the `nginx` Package Is Installed
Add the
package
-based unit test:it { is_expected.to contain_package('nginx') }
- Test That the `nginx` service Is Started, Enabled, and Able to Be Restarted
Add the basic
service
test:it { is_expected.to contain_service(‘nginx’) }
Refine the test by adding the required parameter information:
it { is_expected.to contain_service(‘nginx’).with(ensure: ‘running’, enable: true, hasrestart: true) }
- Test the Contents of the Static Configuration File
Create a
case
statement for both distros within thecontext
block:case os_facts[:osfamily]
when ‘Debian’
when ‘RedHat’
endCheck that the file exists:
case os_facts[:osfamily]
when ‘Debian’
it { is_expected.to contain_file(‘/etc/nginx/nginx.conf’).with_source(‘puppet:///modules/nginx/Debian.conf’) }
when ‘RedHat’
it { is_expected.to contain_file(‘/etc/nginx/nginx.conf’).with_source(‘puppet:///modules/nginx/RedHat.conf’) }
endSave and exit.
Run the unit test:
sudo pdk test unit