Search code examples
unit-testingrspecchef-infrachefspec

Expect raised error at compile time with ChefSpec


My Chef cookbook is raising a compile time error which I want to expect in a ChefSpec test.

Cookbook Snippet

if !windows_version.windows_server_2012_r2? 
    error = "Not supported on this version of Windows"
    raise error
end
windows_package 'Server2012 Only Package' do
    action :install
end

Unit Test Snippet

it 'Throws error' do
    expect(chef_run).to raise_error
end

But this does not catch the error and pass the test. I receive the compile time error instead and the test fails.


Solution

  • You must use curly brackets when testing exception with RSpec:

    it 'Throws error' do
        expect { chef_run }.to raise_error
    end