使用 RSpec 为每个用户角色重复测试描述 [英] Repeated test descriptions with RSpec for every user role

查看:35
本文介绍了使用 RSpec 为每个用户角色重复测试描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 RSpec 创建一些控制器测试,我发现自己为每个可能的用户角色重复了几个测试用例.

Creating some controller tests with RSpec, I find myself repeating several test cases for every possible user role.

例如

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

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

This is a simple example just to make my point, but I have a lot of tests that are repeated... Of course there are also some tests that are unique for each context, but it doesn't matter here.

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

Is there a way to write the tests only once, and then run them in the different contexts?

推荐答案

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​​ 的迭代器.考虑到您的特定实现,您必须调整代码,但这为您提供了正确的想法来完善您的规范.

You can use ruby's iterators in your specs. Given your particular implementation you'll have to adjust the code, but this give you the right idea for DRY'ing out your specs.

此外,您还需要进行必要的调整,以便您的规格清晰易读.

Also you'll need to make the necessary adjustments so your specs read well.

这篇关于使用 RSpec 为每个用户角色重复测试描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆