使用Rspec,运行几个选项中的每个选项?

时间:2011-10-13 16:35:23

标签: ruby testing rspec

我想多次运行一组给定的测试 - 一次作为每个基本类型的系统用户。 (它测试了应该由它们共享的各种功能)。更一般地说,我经常最终想要在不同条件下运行相同的测试集。

run_as_each(user_list) do |user|
  describe "When visiting the front page with #{user.name}" do
    it "should see the welcome message" do
      ....
    end
    it "should be able to login" do
      ....
    end
  end     
end

但这不起作用 - 它说我的方法“run_as_each”是未定义的 - 事实上,似乎帮助者只能在实际的特定测试中使用,“它”。那我该怎么办?

那么我能解决这个问题的另一种方法是什么 - 具体来说,为几个不同的用户运行一批测试,或者至少在测试中定义应该运行哪些用户?

2 个答案:

答案 0 :(得分:1)

您是否考虑过使用共享示例?你提到了用户类型,所以这样的东西可能有用。

shared_examples "a user" do
  let(:user) { described_class.new }

  describe "When visiting the front page" do
    it "should see the welcome message" do
      ....
    end
    it "should be able to login" do
      ....
    end
  end
end

describe UserTypeA do
  it_behaves_like 'a user'
end

describe UserTypeB do
  it_behaves_like 'a user'
end

我没有运行代码,因此很可能出现语法错误。 More from the docs

答案 1 :(得分:0)

我能够通过包含一个带有命名空间模块的文件来解决这个问题,该模块包含了我需要用于动态代码生成的所有“帮助”方法。实际的测试助手(如果通过rspec配置包含)仅在执行测试时加载 - 因此,它们不可用于测试之外的任何代码。