Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Testing with Test Kitchen

ChefSpec: Fast Unit Tests for Recipes

Learn ChefSpec for Chef recipes: how it converges without changing a machine, common matchers, stubbing, platform mocking, and write unit tests with a Ruby stand-in.

Test Kitchen is realistic but slow. A ChefSpec test is the opposite: it runs in a fraction of a second, because it does not touch any machine. ChefSpec loads your recipe, runs Chef's compile phase, builds the resource collection, and records what the resources would do. It never executes them. Then you write assertions such as "this recipe installs nginx and renders /etc/nginx/nginx.conf".

This lesson shows the real ChefSpec syntax (read-only here) and then builds a tiny working imitation in Ruby, so you can practice the idea of "run the recipe in a simulator and assert on the resource collection" with real test code.

Chef and ChefSpec are not installed on this site. The ChefSpec blocks are real and read-only. The runnable code is a clearly labelled stand-in that records resources instead of executing them.

A first ChefSpec test

Ruby
# spec/unit/recipes/default_spec.rb
require 'chefspec'

describe 'myapp::default' do
  platform 'ubuntu', '24.04'

  context 'with default attributes' do
    it 'installs nginx' do
      expect(chef_run).to install_package('nginx')
    end

    it 'renders the config file' do
      expect(chef_run).to create_template('/etc/myapp/app.conf').with(
        owner: 'root',
        mode: '0644'
      )
    end

    it 'enables and starts the service' do
      expect(chef_run).to enable_service('nginx')
      expect(chef_run).to start_service('nginx')
    end

    it 'does not install the debug tools' do
      expect(chef_run).not_to install_package('strace')
    end
  end
end

describe 'myapp::default' names the recipe, platform fakes the operating system with Fauxhai data (a catalog of recorded Ohai output), and chef_run is a converged simulation. The matcher names are built from the action and resource type: install_package, create_template, start_service, run_execute, create_directory.

Run all specs with chef exec rspec (or rspec). A typical suite of 100 examples finishes in seconds.

Testing conditions and attributes

Change attributes in a context to test branches of the recipe:

Ruby
context 'when TLS is enabled' do
  override_attributes['myapp']['tls'] = true

  it 'creates the certificate directory' do
    expect(chef_run).to create_directory('/etc/myapp/certs')
  end
end

context 'on RHEL' do
  platform 'almalinux', '9'

  it 'installs the httpd package instead' do
    expect(chef_run).to install_package('httpd')
  end
end

Use step_into when you want ChefSpec to run the inside of a custom resource, and stubs_for_command / stub_command for guards such as only_if 'test -f /etc/ready' and not_if strings, which ChefSpec refuses to run for real:

Ruby
before do
  stub_command('test -f /etc/myapp/initialized').and_return(false)
end

What ChefSpec cannot tell you

It checks that the recipe declares the right resources, not that they work. A typo in a package name that exists in your recipe and your test passes both. A service that fails to start on a real OS passes too. That is why ChefSpec and Test Kitchen are partners: ChefSpec for logic and branches, Test Kitchen for behavior.

flowchart LR
  A["Recipe change"] --> B["Cookstyle: style and bugs, seconds"]
  B --> C["ChefSpec: resource collection, seconds"]
  C --> D["Test Kitchen + InSpec: real machine, minutes"]

Run the cheap checks first; each layer catches different mistakes.

A runnable imitation

The stand-in below records resources in a collection instead of executing them, evaluates a recipe in a simulated node, and lets you write assertions with tiny matcher helpers. It is the same architecture in about fifty lines.

Ruby Stand-in: a mini ChefSpec

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

All examples pass except the last one, which fails on purpose: the recipe uses port 8080, so the expectation of 80 is false. That is what a failing ChefSpec example looks like, minus the colored diff. Reading the failure tells you which behavior of the recipe is different from the expectation.

Habits of good ChefSpec suites

  • Test behavior, not implementation. Assert on what the node ends up with, not how many resources the recipe contains.
  • Cover each branch once. One example per if, per platform and per feature flag.
  • Use platform and Fauxhai to test several operating systems without VMs.
  • Keep specs independent. Every chef_run starts fresh, so there is no state to clean up.
  • Do not duplicate the recipe. An example that repeats the exact code adds no information; test the outcomes that matter (security-relevant mode, correct port, notifications).
  • Run in CI on every pull request, before the slower Kitchen jobs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ChefSpec do with the resources in a recipe?

    ChefSpec simulates the converge: resources are recorded, not executed, which is why it is fast and safe.
  2. 2. Which matcher checks that a package would be installed?

    Matcher names combine the action and the resource type: install_package, create_template, start_service.
  3. 3. Why does ChefSpec need stub_command for a not_if string guard?

    ChefSpec does not execute shell commands, so it requires you to stub the result of guard commands.
  4. 4. What can ChefSpec NOT detect?

    It only checks declarations. Real behavior needs Test Kitchen with InSpec.

Summary

  • ChefSpec converges a recipe in a simulator and lets you assert on the recorded resources; it is fast and needs no machine.
  • Matchers read like install_package, create_template, start_service; use platform and attribute overrides to test branches.
  • Stub guard commands and use step_into for custom resources.
  • It cannot prove real behavior: pair it with Test Kitchen and InSpec.

Next: InSpec and Cookstyle: Verify and Lint