如何編寫ruby_block的ChefSpec單元測試?如果局部變量是在配方中聲明的呢?它將如何處理?如何爲ruby_block資源編寫ChefSpec單元測試?
這裏有一個配方代碼:
package 'autofs' do
action :install
end
src = '/etc/ssh/sshd_config'
unless ::File.readlines(src).grep(/^PasswordAuthentication yes/).any?
Chef::Log.warn "Need to add/change PasswordAuthentication to yes in sshd config."
ruby_block 'change_sshd_config' do
block do
srcfile = Chef::Util::FileEdit.new(src)
srcfile.search_file_replace(/^PasswordAuthentication no/, "PasswordAuthentication yes")
srcfile.insert_line_if_no_match(/^PasswordAuthentication/, "PasswordAuthentication yes")
srcfile.write_file
end
end
end
unless ::File.readlines(src).grep('/^Banner /etc/issue.ssh/').any?
Chef::Log.warn "Need to change Banner setting in sshd config."
ruby_block 'change_sshd_banner_config' do
block do
srcfile = Chef::Util::FileEdit.new(src)
srcfile.search_file_replace(/^#Banner none/, "Banner /etc/issue.ssh")
srcfile.insert_line_if_no_match(/^Banner/, "Banner /etc/issue.ssh")
srcfile.write_file
end
end
end
由於我是新來ChefSpec,我能夠編寫代碼的基本資源。我寫了如下單元測試:
require 'chefspec'
describe 'package::install' do
let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04').converge(described_recipe) }
it 'install a package autofs' do
expect(chef_run).to install_package('autofs')
end
it 'creates a ruby_block with an change_sshd_config' do
expect(chef_run).to run_ruby_block('change_sshd_config')
end
it 'creates a ruby_block with an change_sshd_banner_config' do
expect(chef_run).to run_ruby_block('change_sshd_banner_config')
end
end
上面的實現是否正確?我無法弄清楚如何將它寫入像ruby block等複雜資源。以及如何在配方中聲明局部變量時應該注意。 在此先感謝..
那麼,這是你可以做的。 ChefSpec不運行ruby_block,它只是檢查,如果ruby_block在資源集合中有正確的動作。爲了測試ruby塊的結果,你必須編寫集成測試,例如使用test-kitchen和inspec。 –