【问题标题】:Repeated test descriptions with RSpec for every user role使用 RSpec 为每个用户角色重复测试描述
【发布时间】:2011-01-13 15:42:47
【问题描述】:

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

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

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

【问题讨论】:

    标签: ruby-on-rails testing rspec2


    【解决方案1】:

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

    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
    

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

    【讨论】:

      【解决方案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​​ 的迭代器。鉴于您的特定实现,您将不得不调整代码,但这为您提供了正确的想法来干燥您的规范。

      此外,您还需要进行必要的调整,以使您的规格能够很好地阅读。

      【讨论】:

      • 我实际上赞成 shared_examples 答案,但在使用 rspec 一段时间后,我更喜欢这种更简单/更容易理解的方法。
      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 2021-12-10
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多