Stub Chef guard_interpreter for ChefSpec test

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’)”

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

describe ‘my_cookbook::my_recipe’ do
  let(:chef_run) do do |node, server|
      stub_chef_server(node, server)

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

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

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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: