关于Ruby / ChefSpec编码风格的反馈

时间:2013-03-05 13:42:08

标签: ruby rspec chef chefspec

我对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', '6.3'],
    "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

欢迎提出任何反馈意见。谢谢!

1 个答案:

答案 0 :(得分:6)

首先,通常的做法是将ChefRunner实例化提取到let助手。您还可以在那里包含所有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

expect语法似乎recommended超过should。但在这个例子中,我会使用单行:

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', '10.04'],
    'centos'   => ['5.8', '6.0', '6.3'],
    'redhat'   => ['5.8', '6.3'],
    'mac_os_x' => ['10.6.8', '10.7.4', '10.8.2'],
    'windows'  => ['2008R2']
  }

  platforms.each do |platform, versions|
    versions.each do |version|
      include_examples 'foo', platform, version
    end
  end
end