Rspect - Rails:如何将值从 let 传递到共享示例 it_behaves_like

问题描述 投票:0回答:1

我想使用变量

RSpec.shared_examples 'something' do |event_name, event_params, action:|
  let(:event_params_data) do
    next instance_exec(&event_params) if event_params.respond_to?(:call)

    event_params
  end

  it 'it does something' do
    puts event_params
    puts event_name

    instance_exec(&action)
  end
end

在另一个规范测试文件中,它使用 it_behaves_like 调用共享示例

describe '#do_alot_of_things' do

   let(:event_params){
     value: 'Value'
   }

   it_behaves_like 'something' 'event_name' {
     passed_value = event_params[:value]
   }

   action: {
     puts 'callback'
   }
end

但是这是不可能的,我收到一个错误,上面写着

`event_params` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc).

您会如何推荐我,以便我能够将测试中定义的值传递给shared_example?将值移动到shared_example中是行不通的,因为锁定shared_example是毫无意义的

ruby-on-rails ruby rspec-rails
1个回答
0
投票

这是如何在共享示例内部/外部使用

let
,以及如何向其传递参数:

RSpec.shared_examples "something" do |bar|
  let(:foo) { "foo" }

  it "uses let/argument" do
    expect(foo).to eq("foo")
    expect(bar).to eq("foo")
  end
end

RSpec.describe SomeClass do
  let(:bar) { "bar" }
  it_behaves_like "something", bar
end
© www.soinside.com 2019 - 2024. All rights reserved.