如何为 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
上述实现是否正确?我无法弄清楚如何为红宝石块等复杂资源编写它。以及如何注意配方中声明的局部变量。提前致谢..