如何在 RSPEC 中多次重复使用同一个测试

How to reuse the same test multiple times in 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

最好的方法是什么?

你几乎成功了。只需删除 describebeforeit 块并在普通方法中移动该代码。

您可以将这些测试变成 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