簡體   English   中英

如何為ruby_block資源編寫ChefSpec單元測試?

[英]How to write ChefSpec Unit Test for ruby_block resource?

如何編寫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等的復雜資源編寫它。如何注意在配方中聲明的局部變量。 提前致謝..

 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

我希望這有幫助!

單元測試應該測試特定的輸入產生預期的輸出。 期望Chef具有run_ruby_block ,實際上是在說“ Chef是否按照我期望的方式工作” –不是,“我的ruby_block資源是否按我期望的方式工作”。

您應該使用ChefSpec以驗證的副作用ruby_block是你期望的是什么。 即,文件被修改。 您可能正在尋找RenderFileMatchers上的ChefSpec文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM