Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Testing and Code Management

RSpec-puppet Unit Tests

Write unit tests for Puppet code with rspec-puppet: compile catalogs per OS with facts, assert resources and relationships, test defines and functions, and fixtures.

Linting tells you the code is well formed. It does not tell you that profile::webserver actually declares an apache service on Debian. Unit tests for Puppet compile a catalog in memory, for a pretend node with facts you choose, and then assert things about the resources in it. They need no virtual machines, they run in seconds, and they are how mature module authors catch regressions.

The standard tool is rspec-puppet, an extension of Ruby's RSpec test framework. This lesson shows the layout, the matchers and the patterns. The tests are Ruby files run with the rspec command, so the examples are read-only; the runnable blocks at the end are JavaScript stand-ins that mimic "compile a catalog from facts and assert on it".

Layout and setup

Tests live in spec/classes, spec/defines, spec/functions and spec/type_aliases. The helper file loads everything:

Ruby
# spec/spec_helper.rb
require 'puppetlabs_spec_helper/module_spec_helper'
require 'rspec-puppet-facts'
include RspecPuppetFacts

Modules that your code depends on are listed in .fixtures.yml, and rake spec_prep downloads them into spec/fixtures/modules before the first test:

YAML
fixtures:
  forge_modules:
    stdlib: "puppetlabs/stdlib"
  symlinks:
    profile: "#{source_dir}"

A first test

A test file mirrors the class name. This one checks that profile::webserver compiles and manages the right resources:

Ruby
# spec/classes/webserver_spec.rb
require 'spec_helper'

describe 'profile::webserver' do
  let(:facts) do
    { os: { family: 'Debian', name: 'Ubuntu' }, networking: { fqdn: 'web1.example.com' } }
  end
  let(:params) { { port: 8080 } }

  it { is_expected.to compile.with_all_deps }
  it { is_expected.to contain_class('apache') }
  it { is_expected.to contain_apache__vhost('shop.example.com').with_port(8080) }
end

What each part does:

  • describe 'profile::webserver' names the class under test.
  • let(:facts) defines the pretend node's facts, and let(:params) the class parameters.
  • compile.with_all_deps compiles the catalog and fails if any resource refers to something that does not exist, or a dependency cycle appears. This one line catches many real bugs.
  • contain_<type>('title') asserts a resource exists. Colons in names turn into double underscores: apache::vhost becomes contain_apache__vhost.
  • .with_port(8080) asserts attribute values. Use .only_with(...) to forbid extra attributes, and .without_xyz to assert that one is absent.

Relationships and ordering

Assert dependencies directly:

Ruby
it { is_expected.to contain_service('apache2').that_requires('Package[apache2]') }
it { is_expected.to contain_file('/etc/apache2/ports.conf').that_notifies('Service[apache2]') }

If a refactoring accidentally removes a notify, this test fails and the "config changes but the service never restarts" bug never reaches production.

Testing against every supported OS

Instead of hand-written facts, rspec-puppet-facts supplies realistic fact sets from the Facterdb project for every OS your metadata.json supports:

Ruby
on_supported_os.each do |os, os_facts|
  context "on #{os}" do
    let(:facts) { os_facts }
    it { is_expected.to compile.with_all_deps }
    it { is_expected.to contain_package(os_facts[:os]['family'] == 'Debian' ? 'apache2' : 'httpd') }
  end
end

One loop, one test per OS, with no virtual machines. When someone adds Rocky Linux to metadata.json, the new combination is tested automatically.

Defines, functions and error cases

Test a defined type with a title:

Ruby
describe 'profile::vhost' do
  let(:title) { 'shop.example.com' }
  let(:params) { { port: 443 } }
  it { is_expected.to contain_file('/etc/apache2/sites/shop.example.com.conf') }
end

Test a function by calling it with arguments:

Ruby
describe 'profile::buffer_mb' do
  it { is_expected.to run.with_params(8 * 1024**3).and_return(2048) }
  it { is_expected.to run.with_params('x').and_raise_error(ArgumentError) }
end

And expected failures: a class that calls fail() for an unsupported OS needs a test too:

Ruby
context 'on an unsupported OS' do
  let(:facts) { { os: { family: 'Solaris' } } }
  it { is_expected.to compile.and_raise_error(/Unsupported OS family/) }
end

What to test, and what not to

A good unit test says what the code promises, not how it is written:

  • Test the contract: key resources exist, important relationships hold, parameters flow through, error cases fail clearly.
  • Do not copy the manifest into the test line by line; that only doubles your maintenance.
  • Cover each role with a single "compiles for every supported OS" test. This is the highest value test in a roles and profiles codebase.
  • Keep acceptance behavior (does Apache really answer on port 8080?) for Litmus.

Stand-ins: compile and assert

The following is a JavaScript stand-in. A function plays the role of the catalog compiler (facts and params in, a list of resources out) and a few helper functions imitate contain_*, with_* and that_requires. It shows the shape of the testing approach, not rspec-puppet itself.

JS Stand-in: compile a catalog and assert on it

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: detect an unresolved dependency like compile.with_all_deps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

flowchart LR
  F["facts and params"] --> C["catalog compiler in memory"]
  C --> R["resources and relationships"]
  R --> A["matchers: contain_*, with_*, that_requires"]
  A --> P["pass / fail"]

Unit tests compile; they do not change a machine.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does it { is_expected.to compile.with_all_deps } verify?

    It compiles the catalog and checks relationships; it does not touch a machine.
  2. 2. How is the resource apache::vhost written in a matcher?

    Colons in type names become double underscores in matcher names.
  3. 3. What supplies realistic facts for every supported OS?

    rspec-puppet-facts reads Facterdb data for the OSes in metadata.json.
  4. 4. Which test belongs in acceptance (Litmus) rather than unit tests?

    Observing real behavior on a machine is an acceptance concern.

Summary

  • rspec-puppet compiles catalogs in memory, with facts and parameters you choose, and asserts on resources.
  • compile.with_all_deps is the single most valuable assertion.
  • Use on_supported_os to cover every supported platform without virtual machines.
  • Test defines (title), functions (run.with_params) and expected failures too.
  • Test the contract, not the line-by-line implementation.

Next: PDK and Module Development