使用动态计算参数调用共享示例

Calling shared examples with dynamic computed parameters

我是水豚的新手,rspec 集成测试。 如何使用动态计算的参数调用共享示例?

shared_examples_for "a measurable object" do |example, display_name|
    it "is example - #{display_name}" do
      visit "www.example.com?args=test"
      expect(page.find("#examplediv").text).to eq example 
    end
end

describe "example" do
  # where to compute this dynamic_value
  it_behaves_like "a measurable object", dynamic_value, "example 1"
end

描述和 shared_example 都在不同的文件中。

在上面的代码片段中,我想根据从方法调用中获得的数据计算 dynamic_value。

我在哪里计算 "dynamic_value" 的值?

我已经尝试在 before :eachbefore :all 中进行计算,但都没有用。

如果你用describe给我解释一下调用周期就好了。

提前致谢。

好吧,我仍然不是 100% 确定我理解你的意图,但我想我现在已经足够提供一个基本的解释了。我会这样实现这个概念:

shared_examples_for "a page parser" do |dom_object,value|
  it "the text in #{dom_object} should equal #{value} on #{url}" do
    visit url
    expect(page.find("##{dom_object}").text).to eq value
  end
end

describe "example" do
  let(:url) { "www.example.com?args=test" }    
  values_obtained_from_service_call = Service.call(url)
  # We will assume this is something like [{dom_object: examplediv, value: "Hello World!"}]
  values_obtained_from_service_call.each do |test| 
    it_should_behave_like "a page parser", test[:dom_object], test[:value]
  end
end

这将遍历 values_obtained_from_service_call 并使用共享示例测试它们。

正如我所说,我仍然不确定您为什么要这样做,但从功能上讲它应该可以工作。