如何为ruby_block资源编写ChefSpec单元测试?

时间:2017-05-11 08:45:16

标签: ruby unit-testing chef devops chefspec

如何为ruby_block编写ChefSpec Unit测试?如果在配方中声明了局部变量怎么办?如何处理?

以下是食谱的代码:

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块等)编写它。以及如何处理在配方中声明的局部变量。 提前谢谢..

2 个答案:

答案 0 :(得分:1)

 let(:conf) { double('conf') }
    before do
      allow(File).to receive(:readlines).with('/etc/ssh/sshd_config').and_return(["something"])
      allow(File).to receive(:readlines).with('/etc/ssh/sshd_config').and_return(["something"])
end

 it 'creates a ruby_block with an change_sshd_config' do
    expect(chef_run).to run_ruby_block('change_sshd_config')
    expect(Chef::Util::FileEdit).to receive(:new).with('/etc/ssh/sshd_config').and_return(conf)
    confile = Chef::Util::FileEdit.new('/etc/ssh/sshd_config')
  end

对其他红宝石块做同样的事情!通常它会起作用。

或者

您可以使用inspec测试您的系统状态。看来你可能想要测试系统的状态,以便在Chef应用config之后配置sshd的方式。你可以通过inspec实现这一点,例如以下代码片段:

describe file('/etc/ssh/sshd_config') do
  its('content') { should match /whatever/ }
end

我希望这有帮助!

答案 1 :(得分:0)

单元测试应测试特定输入产生预期输出。通过期望Chef拥有run_ruby_block,您实际上在说#34; Chef 是否按照我期望的方式工作" - 不是,"我的ruby_block资源是否按照我预期的方式运作,并且#34;。

您应该使用ChefSpec来验证ruby_block的副作用是否符合您的预期。也就是说,文件被修改。 RenderFileMatchers上的ChefSpec文档可能就是您正在寻找的内容。

相关问题