2013-03-05 11 views
6

私はRubyを初めて使っていますが、私は過去2週間シェフテストに関する多くの研究を行っています。このテストではChefSpec & Fauxhaiを使用していますが、 "ruby-ish"のようには見えず、コミュニティがコーディングスタイルについていくつか指摘してくれることを期待していました。このようなネストされたループを書く良い方法はありますか?Ruby/ChefSpecコーディングスタイルへのフィードバック

料理/ fooの/レシピ/ default.rb

package "foo" do 
    action :install 
end 

料理/ fooの/スペック/ 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 

任意およびすべてのフィードバックは大歓迎です。ありがとうございました!

+2

https://github.com/bbatsov/ruby-style-guideはRubyコーディングの推奨ガイドラインの一般的な参考資料です。私は可読性を維持しながら、それらの入れ子にされたループをきれいにするためにできることはたくさんあるとは思わない。 –

+0

私はガイドを読んだことがありますが、改善することはできません。フィードバックをお寄せいただきありがとうございます! – Rapsey

答えて

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構文はshouldオーバーrecommendedのようです。あなたがRSpec's shared examplesを使用することができますループビットをクリーンアップするには

subject do 
    ChefSpec::ChefRunner.new(platform: platform, version: version).converge('foo::default') 
end 
it { should install_package 'foo' } 

:しかし、この例では、私はワンライナーを使用します。もう少し拡張された例:

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 
+0

もう1つの方法は、RSpecタグ( 'describe 'foo'、プラットフォーム:[...] do ...)を使用し、それに基づいて共有例をループすることです。 –

関連する問題