Chefspec execute resource with cwd


#1

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.

thanks,

Brian Phalane


#2

Hi,

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'])
  end
end

[1] https://github.com/chefspec/chefspec#making-assertions


#3

This is how i wrote it so far

recipe

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

spec

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

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?

Thanks


#4

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.


#5

Hi @joerg.herzinger,

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

Thanks,


#6

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')


#7

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

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

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


#8

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


#9

After removing the whitespace it worked. :grinning:

Thanks guys