针对每个用户角色使用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 

这是一个简单的例子,只是为了表明我的观点,但我有很多重复的测试…当然也有一些测试对每个上下文都是唯一的,但这并不重要。

有没有办法只编写一次测试,然后在不同的上下文中运行它们?

 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的迭代器。 鉴于您的特定实现,您将不得不调整代码,但这为您提供干燥规格的正确理念。

此外,您还需要进行必要的调整,以便您的规格读得很好。

共享示例是一种更灵活的方法:

 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文件中,以减少重复。 在检查身份validation/授权时,这在控制器测试中很有效,这通常会导致重复测试。