针对每个用户角色使用RSpec重复测试描述

Mar*_*ino 4 testing ruby-on-rails rspec2

使用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
Run Code Online (Sandbox Code Playgroud)

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

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

zet*_*tic 15

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

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

在这个例子中

describe "GET 'index'" do
  context "for admin user" do
    login_user("admin")
    it_behaves_like "titled"
  end
end
Run Code Online (Sandbox Code Playgroud)

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


Geo*_*son 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
Run Code Online (Sandbox Code Playgroud)

您可以在规范中使用 ruby​​ 的迭代器。鉴于您的特定实现,您必须调整代码,但这为您提供了干燥规范的正确想法。

此外,您还需要进行必要的调整,以便您的规格易于阅读。