Chefspec execute resource with cwd


HI, i am trying to write tests for my recipe that has the “execute” resource,which specifies the “cwd” and has “command”. i was wondering if it’s possible to do a test/check on the “cwd” part.


Brian Phalane



You can check any property of a resource with with (not a typo :slight_smile: ). The checspec docs have this [1]

require 'chefspec'

describe 'example::default' do
  let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }

  it 'adds the member vagrant to the docker group' do
    expect(chef_run).to modify_group('docker').with(members: ['vagrant'])



This is how i wrote it so far


execute ‘clean directory’ do
cwd ‘/my/current/working/directory’
command ‘rm -f .gz


it ‘clean directory’ do
expect(chef_run).to run_execute(‘rm -f*.gz*’)

my problem with this is, if someone modify the cwd “/my/current/working/directory” , tests will still pass. which is not correct.

My question is, is it possible to stub it, or allow with cwd to be checked/tested?



Yes, it is possible. Please read my answer and read the Documentation in the link I posted.
And for future topics, please use the formatting provided by this forum for better readability.


Hi @joerg.herzinger,

I still haven’t figure this out. do you mind helping? all cases i have tried, gives me error.



Ok, so two things:
1: You have to test against the resource and identify them by their name. Your execute is called “clean directory” while you try to find the command.
2: You can test the properties with “with” passing a hash.

So in end you need something like this expect(chef_run).to run_execute('clean directory').with( command: 'rm -f *.gz', cwd: '/dir/ecto/ry')


This is the same i have been trying, however i did not succeed

  1. INT3_Backend::default When all attributes are default, on Ubuntu 16.04 clean dir
    Failure/Error: expect(chef_run).to run_execute (‘clean dir’).with(command: ‘rm -f .gz’,cwd: ‘/export/home/devopadm’)

    undefined method `with’ for “clean dir”:String

    ./spec/unit/recipes/default_spec.rb:25:in `block (3 levels) in <top (required)>’


You put a space between run_execute and ('clean dir'). That is not allowed.


After removing the whitespace it worked. :grinning:

Thanks guys