如何在RSPEC中多次重复使用相同的测试

时间:2015-05-07 14:36:12

标签: ruby-on-rails rspec

在我的一个rspec测试文件中,我需要在几个不同的上下文中运行以下(相同的)测试:

describe "view the event with request" do
  before {
    click_link("Swimming lessons")
  }

  it { should have_content "Party Supplies"}

  describe "view the contribute form" do
    before {
      click_button("Party Supplies")
    }

    it {
      within("#bodyPopover") {
        should have_content('cupcakes')
        should have_content('napkins')
      }
    }


  end

end

我希望能够将所有这些放在一个方法中(比如view_the_event_and_contribute_form),并在其余的测试中在几个地方使用该方法。这可以实现吗?我尝试定义一个只有该代码的方法,但它不能从该方法中识别describe

最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以将这些测试转换为shared_example

shared_example "event with request" do
  before { click_link("Swimming lessons") }

  it { should have_content "Party Supplies"}

  describe "view the contribute form" do
    before { click_button("Party Supplies") }

    specify {
      within("#bodyPopover") {
        should have_content('cupcakes')
        should have_content('napkins')
      }
    }
  end
end

从其他测试中使用it_behaves_like来运行共享示例:

describe 'Some other awesome tests' do
  it_behaves_like "event with request"
end

答案 1 :(得分:0)

你几乎拥有它。只需删除describebeforeit块,然后在普通方法中移动该代码。