Unit Testing Puppet with rspec-puppet: Classes, Defines, Hiera and Catalog Compile
What Unit Tests Do
rspec-puppet compiles your code into a catalog (no real server changed) and lets you check what is inside: 'is the package there? is the file notified to the service?'. Tests run in seconds on a laptop. They catch typos, missing dependencies and logic errors before deployment.
Setup
text
mymodule/
manifests/ templates/ data/ hiera.yaml
spec/
spec_helper.rb
default_facts.yml
classes/ntp_spec.rb
defines/vhost_spec.rb
functions/...
fixtures/ (downloaded modules, created by the fixtures tool)
.fixtures.yml
Gemfile Rakefile
ruby
# spec/spec_helper.rb (the PDK generates this)
require 'puppetlabs_spec_helper/module_spec_helper'
require 'rspec-puppet-facts'
include RspecPuppetFacts
RSpec.configure do |c|
c.default_facts = { 'networking' => { 'hostname' => 'testnode', 'fqdn' => 'testnode.example.com' } }
c.after(:suite) { RSpec::Puppet::Coverage.report!(80) } # fail if less than 80% of resources are covered
end
yaml
# .fixtures.yml
fixtures:
forge_modules:
stdlib: puppetlabs/stdlib
symlinks:
ntp: "#{source_dir}"
bash
pdk test unit # easiest, includes all the setup
# or with bundler:
bundle install
bundle exec rake spec_prep spec spec_clean
bundle exec rspec spec/classes/ntp_spec.rb -fd
Your First Test
ruby
# spec/classes/ntp_spec.rb
require 'spec_helper'
describe 'ntp' do
let(:facts) do
{ os: { 'family' => 'RedHat', 'name' => 'Rocky', 'release' => { 'major' => '9' } } }
end
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('ntp::install') }
it do
is_expected.to contain_package('chrony').with(
ensure: 'installed',
)
end
it do
is_expected.to contain_file('/etc/chrony.conf').with(
ensure: 'file',
owner: 'root',
mode: '0644',
).with_content(%r{^pool pool\.ntp\.org})
end
it { is_expected.to contain_service('chronyd').with_ensure('running').with_enable(true) }
end
| Matcher | Checks |
compile, compile.with_all_deps | Catalog builds, and all relationship targets exist |
contain_package('x') | A resource is in the catalog |
.with(ensure: 'installed'), .with_ensure(...) | Attribute values |
.without_source, .only_with(...) | An attribute is absent, or only these are set |
.with_content(/regex/), .without_content(/regex/) | File content (rendered from the template) |
.that_requires('Package[x]') | Dependency |
.that_notifies('Service[x]'), .that_subscribes_to(...), .that_comes_before(...) | Relationships and ordering |
contain_class('x'), contain_ntp__vhost('title') | Classes and defined types (:: becomes __) |
have_resource_count(10), have_package_resource_count(1) | Counts |
raise_error(/regex/) | The code must fail with this message |
Parameters
ruby
context 'with custom servers' do
let(:params) { { servers: ['time1.example.com', 'time2.example.com'] } }
it { is_expected.to contain_file('/etc/chrony.conf').with_content(%r{server time1\.example\.com}) }
end
context 'with an invalid parameter' do
let(:params) { { servers: 'not-an-array' } }
it { is_expected.to compile.and_raise_error(%r{expects an Array value}) }
end
context 'on an unsupported OS' do
let(:facts) { { os: { 'family' => 'Solaris' } } }
it { is_expected.to compile.and_raise_error(%r{unsupported}i) }
end
Many Operating Systems at Once: on_supported_os
rspec-puppet-facts uses facterdb, a database of real facts for many OS versions. on_supported_os reads the OS list from metadata.json and runs your test for each one.
ruby
describe 'ntp' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
it { is_expected.to compile.with_all_deps }
case os_facts[:os]['family']
when 'RedHat'
it { is_expected.to contain_service('chronyd') }
when 'Debian'
it { is_expected.to contain_service('chrony') }
end
end
end
end
Testing Defined Types
ruby
# spec/defines/vhost_spec.rb
require 'spec_helper'
describe 'webapp::vhost' do
let(:title) { 'shop.example.com' }
let(:params) { { docroot: '/var/www/shop', port: 8080 } }
let(:pre_condition) { "service { 'nginx': }" } # code that must exist first
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_file('/var/www/shop').with_ensure('directory') }
it do
is_expected.to contain_file('/etc/nginx/conf.d/shop.example.com.conf')
.with_content(%r{listen 8080;})
.that_notifies('Service[nginx]')
end
end
| Helper | Use |
let(:title) | Title of the defined type or resource |
let(:params) | Parameters |
let(:facts) | Facts (with on_supported_os or your own) |
let(:node) | Certname |
let(:pre_condition) | Puppet code before the class under test (for dependencies) |
let(:post_condition) | Puppet code after it |
let(:trusted_facts) | Trusted data such as { 'pp_role' => 'webserver' } |
Testing Hiera Data
ruby
describe 'profile::nginx' do
let(:facts) { on_supported_os['ubuntu-24.04-x86_64'] }
context 'with Hiera data from the module/environment' do
let(:hiera_config) { 'spec/fixtures/hiera.yaml' } # a test hiera.yaml
it { is_expected.to contain_class('nginx').with_manage_repo(true) }
end
end
yaml
# spec/fixtures/hiera.yaml
---
version: 5
defaults:
datadir: spec/fixtures/hieradata
data_hash: yaml_data
hierarchy:
- name: common
path: common.yaml
Testing Templates
Because the catalog contains the rendered file content, with_content tests the template output. For complex templates, test several parameter combinations or compare the whole output.
ruby
it 'renders every server line' do
expect(catalogue.resource('file', '/etc/chrony.conf')[:content]).to eq(<<~CONF)
# Managed by Puppet
server time1.example.com iburst
server time2.example.com iburst
CONF
end
Testing Functions
ruby
# spec/functions/format_name_spec.rb
describe 'mymodule::format_name' do
it { is_expected.to run.with_params('web01').and_return('WEB01') }
it { is_expected.to run.with_params(nil).and_raise_error(ArgumentError) }
end
Coverage
Add RSpec::Puppet::Coverage.report! (see spec_helper.rb) to see which resources have no test. Coverage is a useful signal, but a good test checks behaviour, not just that a resource exists.
Good Habits
- Always have at least
compile.with_all_deps for every class and OS
- Test the logic: conditions, loops, and error branches
- Do not test Puppet itself (for example that
package installs). Test your decisions
- Keep tests readable and small
- Run unit tests in CI on every pull request
- Update fixtures and facterdb regularly, to test against the OS versions you run
Practice Tasks
- Write a spec for your
ntp class that tests two operating systems with on_supported_os
- Add a test that a wrong parameter type raises an error
- Test a defined type with
pre_condition
- Add a test that checks the rendered template content
- Run
pdk test unit and fix any failing test
Conclusion
rspec-puppet builds the catalog and lets you assert what is in it. Always include compile.with_all_deps, loop through supported operating systems, test parameters and error cases, and run the tests in CI.
Quick Summary: rspec-puppet = catalog assertions; compile.with_all_deps; on_supported_os; .with()/.that_notifies; pre_condition; hiera_config.