0

I am trying to write a ChefSpec test to check that the recipe creates a directory only if it doesn't exist. I get my first test of "creating directory" pass but the second test fails. The recipe is down below. Can someone please help in getting the second part right? Because if the directory exists, then the first test fails. I have to delete the directory to make the first test pass and then the second test fails anyway.

require 'spec_helper'

describe 'my_cookbook::default' do
  context 'Windows 2012' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'Windows', version: '2012')
      runner.converge(described_recipe)
    end

    it 'converges successfully' do
      expect { chef_run }.to_not raise_error
    end

    it 'creates directory' do
      expect(chef_run).to create_directory('D:\test1\logs')
    end

    it 'checks directory' do
      expect(chef_run).to_not create_directory( ::Dir.exists?("D:\\test1\\logs") )
    end
  end
end

Here is the recipe, which on its own works as intended but I cant seem to write a test around it.

directory "D:\\test1\\logs" do
  recursive true
  action :create
  not_if { ::Dir.exists?("D:\\test1\\logs") }
end
janedoegcp
  • 27
  • 5

1 Answers1

0

not_if or only_if are chef guards:

a guard property is then used to tell the chef-client if it should continue executing a resource

in order to test your directory resource with chefspec, you will have to stub the guard so when chefspec compiles your resources you want the not_if guard to evaluates to either true or false.

In order for ChefSpec to know how to evaluate the resource, we need to tell it how the command would have returned for this test if it was running on the actual machine:

describe 'something' do
  recipe do
    execute '/opt/myapp/install.sh' do
      # Check if myapp is installed and runnable.
      not_if 'myapp --version'
    end
  end

  before do
    # Tell ChefSpec the command would have succeeded.
    stub_command('myapp --version').and_return(true)
    # Tell ChefSpec the command would have failed.
    stub_command('myapp --version').and_return(false)
    # You can also use a regexp to stub multiple commands at once.
    stub_command(/^myapp/).and_return(false)
  end
end
Mr.
  • 9,429
  • 13
  • 58
  • 82