我正在尝试为我的食谱编写chefspec / unit测试。我面临着问题。我需要为下面的代码编写单元测试用例。如果我评论我的代码的最后一个语句,测试执行成功,但我必须捕获该语句,因为它是正确的写入方式。谢谢你的帮助。
powershell_script 'Delete ISO from temp directory' do
code <<-EOH
[System.IO.File]::Delete("#{iso_path}")
[System.IO.File]::Delete("#{config_path}")
EOH
guard_interpreter :powershell_script
only_if { File.exists?(iso_path)}
end
答案 0 :(得分:0)
首先,您的代码没有意义。您有guard_interpreter
集,但您的guard子句是Ruby代码块,而不是命令字符串。除此之外,只需测试它就像其他任何东西。如果您具体指的是如何测试现有文件和不存在文件,则可以使用rspec-mocks
设置File.exists?
以返回固定值。
答案 1 :(得分:0)
首先。如果你只需删除一个文件,并根据这种情况的代码,你应该使用file
资源。
[iso_path, config_path].each do |path|
file path do
action :delete
end
end
File
是幂等资源。这意味着,如果应该更改资源,Chef会为您进行检查。在这种情况下,Chef将删除该文件,只有该文件存在。
Powershell_script
(以及所有其他script
资源)都是非幂等的。这意味着,如果要执行资源,您可以通过提供guard
来检查自己。 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
资源相比还需要做多少工作?