在上下文中删除重复的rspec测试

时间:2015-09-03 21:12:57

标签: ruby-on-rails ruby rspec

假设我有各种RSpec context块来对具有类似数据场景的测试进行分组。

feature "User Profile" do
  context "user is active" do
    before(:each) {  (some setup) }

    # Various tests
    ...
  end

  context "user is pending" do
    before(:each) {  (some setup) }

    # Various tests
    ...
  end

  context "user is deactivated" do
    before(:each) {  (some setup) }

    # Various tests
    ...
  end
end

现在我正在添加一项新功能,我想添加一个简单的方案来验证用户页面上某个链接时的行为

it "clicking help redirects to the user's help page" do
  click_on foo_button
  expect(response).to have('bar')
end

理想情况下,我很乐意为所有3个上下文添加此测试,因为我想确保它在不同的数据场景下正确执行。但是测试本身并没有从上下文变为上下文,因此将它全部输入3次似乎是重复的。

干燥此测试集有哪些替代方案?我可以将新测试粘贴到某个模块中,还是RSpec有一些内置功能让我定义一次并从每个context块调用它?

谢谢!

1 个答案:

答案 0 :(得分:5)

您可以使用shared_examples ...在spec / support / shared_examples.rb中定义它们

shared_examples "redirect_help" do
  it "clicking help redirects to the user's help page" do
    click_on foo_button
    expect(response).to have('bar')
  end
end

然后在每个上下文中输入...

it_behaves_like "redirect_help"

您甚至可以将块传递给it_behaves_like,然后使用action方法执行该块,该块对每个上下文都是唯一的。

您的shared_example可能看起来像......

shared_examples "need_sign_in" do
  it "redirects to the log in" do
    session[:current_user_id] = nil
    action
    response.should render_template 'sessions/new'
  end
end

在你的上下文中,你用块来称呼它......

  describe "GET index" do
    it_behaves_like "need_sign_in" do
      let(:action) {get :index}
    end
    ...
相关问题