First of all. If all you need is to delete a file, and according to the code that is the case, you should use file
resource.
[iso_path, config_path].each do |path|
file path do
action :delete
end
end
File
is idempotent resource. Which means Chef checks for you, if the resource should be changed. In this case Chef will delete the file, only if that exists.
Powershell_script
(and all the other script
resources) are non-idempotent. Which means, you have check yourself, if the resource should be executed, by providing a guard
. Guard is only_if
or not_if
block. You should remove guard_interpreter :powershell_script
line, because you are actually writing ruby in the guard.
powershell_script 'Delete ISO from temp directory' do
code <<-EOH
[System.IO.File]::Delete("#{iso_path}")
[System.IO.File]::Delete("#{config_path}")
EOH
only_if { File.exists?(iso_path) }
end
Now to testing. Testing file
resource is easy, as I understand you already can do that. But testing powershell_script
is harder: you must stub the File.exists?(iso_path)
call. You can do it like that:
describe 'cookbook::recipe' do
context 'with iso file' do
let! :subject do
expect( ::File ).to receive( :exists? ).with( '<iso_path_variable_value>' ).and_return true
allow( ::File ).to receive( :exists? ).and_call_original
ChefSpec::Runner.new( platform: 'windows', version: '2008R2' ).converge described_recipe
end
it { shold run_powershell_script 'Delete ISO from temp directory' }
end
context 'without iso file' do
let! :subject do
expect( ::File ).to receive( :exists? ).with( '<iso_path_variable_value>' ).and_return false
allow( ::File ).to receive( :exists? ).and_call_original
ChefSpec::Runner.new( platform: 'windows', version: '2008R2' ).converge described_recipe
end
it { shold_not run_powershell_script 'Delete ISO from temp directory' }
end
end
Do you see how much more work you have to do comparing to testing file
resource?