Stub Chef guard_interpreter for ChefSpec test

2016/12/20

If you have a Chef cookbook with a resource containing a “guardian”, like, let’s say a PowerShell guard interpreter, you must stub the content of the Chef guard.
Here is an example of the resource using the guardian:

file “some_log_path” do
  guard_interpreter :powershell_script
  action :delete
  not_if “(ls -Dir ‘C:\temp’).Name.Contains(‘build’)”
end

Here’s how you have to construct your ChefSpec file:

describe ‘my_cookbook::my_recipe’ do
  let(:chef_run) do
    ChefSpec::ServerRunner.new do |node, server|
      stub_chef_server(node, server)
    end.converge(described_recipe)
  end

  before do
    stub_command(“(ls -Dir ‘C:\temp’).Name.Contains(‘build’)”).and_return(false)
  end

  it ‘does not raise an exception’ do
    expect { chef_run }.to_not raise_error
  end

  it ‘deletes the existing log file’ do
    expect(chef_run).to delete_file(‘C:\temp\releases\some_build\log.txt’)
  end
end

Advertisements

%d bloggers like this: