2011-01-13 57 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 

你可以在你的規格中使用ruby的迭代器。考慮到你的具體實現,你必須調整代碼,但是這給你正確的想法來幹掉你的規格。

此外,您還需要進行必要的調整,以便您的規格閱讀良好。

+0

非常感謝! – Ian 2011-11-02 18:22:40

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 

共用例子也可以包含在其他spec文件中以減少重複。在檢查認證/授權時,這在控制器測試中效果很好,這通常用於重複性測試。