5

使用 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

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

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

4

3 回答 3

16

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

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

共享示例也可以包含在其他规范文件中以减少重复。当检查身份验证/授权时,这在控制器测试中效果很好,这通常会导致重复测试。

于 2011-01-14T00:52:16.967 回答
3
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​​ 的迭代器。鉴于您的特定实现,您将不得不调整代码,但这为您提供了干燥规范的正确想法。

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

于 2011-01-13T15:48:43.350 回答
1

尝试使用共享示例组

http://relishapp.com/rspec/rspec-core/v/2-4/dir/example-groups/shared-example-group

于 2011-01-13T16:37:05.120 回答