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

标签 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从该方法中。

做到这一点的最佳方法是什么?

最佳答案

您可以将这些测试转换为 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

关于ruby-on-rails - 如何在 RSPEC 中多次重复使用相同的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30104215/

相关文章:

ruby-on-rails - 在 Rails 中深度模块化/命名空间是否正常?我公司的代码库深入 4 到 5 个命名空间,我想知道这是否正常

ruby-on-rails - 如何筛选 Rails 模型中太大的整数?

ruby-on-rails - 无法在 rspec 测试中 stub redis

ruby - 如何创建一个将散列(有或没有指定值)作为参数的方法?

ruby-on-rails - 条件代码 if-else 的 Rspec?

ruby-on-rails - rspec 路由测试和主机

ruby-on-rails - 将选项传递给 ActiveModelSerializers 0.9.0

ruby-on-rails - 尝试在 ruby​​ 中创建 pin 时如何修复 NoMethodError?

ruby-on-rails - RSpec & Tire gem:测试 Tire::Results::Collection

ruby-on-rails - Rails & Redcarpet:在 ApplicationHelper 中使用时未初始化的常量 Redcarpet::Render