首先。如果您只需要删除一个文件,并且根据这种情况的代码,您应该使用fileresource.
[iso_path, config_path].each do |path|
file path do
action :delete
end
end
File是幂等资源。这意味着 Chef 会检查您是否应该更改资源。在这种情况下,Chef 将删除该文件,前提是该文件存在。
Powershell_script(以及所有其他script资源)是非幂等的。这意味着,您已经通过提供guard. 守卫only_if或not_if阻挡。您应该删除guard_interpreter :powershell_script行,因为您实际上是在警卫中编写 ruby。
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
现在进行测试。测试file资源很容易,因为我知道您已经可以做到这一点。但测试powershell_script更难:您必须对File.exists?(iso_path)调用进行存根。你可以这样做:
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
file与测试资源相比,您是否看到还有多少工作要做?