2011-01-13 7 views
4

RSpecを使っていくつかのコントローラテストを作成すると、すべてのユーザロールに対していくつかのテストケースが繰り返されていました。例えばすべてのユーザロールについてRSpecを使ってテストの説明を繰り返しました

describe "GET 'index'" do 
    context "for admin user" do 
    login_user("admin") 

    it "has the right title" do 
     response.should have_selector("title", :content => "the title") 
    end 
    end 

    context "for regular user" do 
    login_user("user") 

    it "has the right title" do 
     response.should have_selector("title", :content => "the title") 
    end 
    end 
end 

これはちょうど私のポイントを作るために簡単な例ですが、私は繰り返してテストをたくさん持っている...もちろん、各コンテキストに対して一意であるいくつかのテストもありますしかし、ここでは関係ありません。

テストを一度しか書いておらず、別のコンテキストでテストを実行する方法はありますか?

答えて

2
describe "GET 'index'" do 
    User::ROLES.each do |role| 
    context "for #{role} user" do 
     login_user(role) 

     it "has the right title" do 
     response.should have_selector("title", :content => "the title") 
     end 
    end 
    end 
end 

仕様では、ルビのイテレータを使用できます。特定の実装を考えれば、コードを調整する必要がありますが、これは仕様をDRYするのに適しています。

また、スペックがうまく読み取れるように調整する必要があります。

+0

Excelent、ありがとうございます! – Ian

+0

私は実際にshared_examplesの回答をupvotedしましたが、しばらくの間はrspecを使用した後、私はこの簡単で分かりやすい方法を好んでいました。 – Dty

14

共有例を使用してみてくださいこれより柔軟なアプローチである:

shared_examples_for "titled" do 
    it "has the right title" do 
    response.should have_selector("title", :content => "the title") 
    end 
end 

および実施例に

describe "GET 'index'" do 
    context "for admin user" do 
    login_user("admin") 
    it_behaves_like "titled" 
    end 
end 

共用例ことができ、また重複を減らすために他のスペックファイルに含めることができます。これは、認証/認可をチェックするときにコントローラテストでうまくいきます。

関連する問題