我对
Ruby很陌生,但过去两周我一直在做大量的厨师测试研究.该测试使用ChefSpec& Fauxhai,但它看起来并不是“ruby-ish”,我希望社区可以给我一些关于编码风格的指示.有没有更好的方法来编写这样的嵌套循环?
食谱/富/食谱/ default.rb
package "foo" do action :install end
食谱/富/规格/ default_spec.rb
require 'chefspec' describe 'foo::default' do platforms = { "debian" => ['6.0.5'],"ubuntu" => ['12.04','10.04'],"centos" => ['5.8','6.0','6.3'],"redhat" => ['5.8',"mac_os_x" => ['10.6.8','10.7.4','10.8.2'],"windows" => ['2008R2'] } platforms.each do |platform,versions| versions.each do |version| context "on #{platform} #{version}" do before do Fauxhai.mock(platform: platform,version: version) end it 'should install foo' do @runner = ChefSpec::ChefRunner.new.converge('foo::default') @runner.should install_package 'foo' end end end end end
欢迎任何和所有反馈.谢谢!
解决方法
首先,一个常见的做法是提取ChefRunner实例化以让佣工.您还可以在那里包含所有Fauxhai配置:
let(:chef_run) do ChefSpec::ChefRunner.new(platform: platform,version: version) do |node| node.set['foo']['bar'] = 'baz' # .... end.converge('foo::default') end it "installs foo" do expect(chef_run).to install_package 'foo' end
应该是期望语法似乎是recommended.但是在这个例子中我会使用一个单行:
subject do ChefSpec::ChefRunner.new(platform: platform,version: version).converge('foo::default') end it { should install_package 'foo' }
要清理循环,可以使用RSpec’s shared examples.更多扩展示例:
require 'chefspec' shared_examples 'foo' do |platform,version| context "on #{platform} #{version}" do let(:users) { %w[user1 user2] } let(:chef_run) do ChefSpec::ChefRunner.new(platform: platform,version: version) do |node| node.set['foo']['users'] = users end.converge('foo::default') end subject { chef_run } it { should install_package 'foo' } it "creates specified users" do users.each { |u| expect(chef_run).to create_user u } end end end describe 'foo::default' do platforms = { 'debian' => ['6.0.5'],'ubuntu' => ['12.04','centos' => ['5.8','redhat' => ['5.8','mac_os_x' => ['10.6.8','windows' => ['2008R2'] } platforms.each do |platform,versions| versions.each do |version| include_examples 'foo',platform,version end end end