如何在嵌套 Rspec 共享示例中传递两个级别的变量?

How do I pass a variable two levels in a nested Rspec shared example?

基本上,我有一堆共享的例子。我认为这会起作用,但我在传递的变量上得到 stack level too deep

shared_examples 'Foo' do
  # top level shared example passes values
  # to a lower-level shared example.
  it_behaves_like 'Bar' do
    let(:variable) { variable }
  end

  it_behaves_like 'Baz'
end

shared_examples 'Bar' do
  it { expect(variable).to veq('value')
end

规格:

describe SomeClass do
  it_behaves_like 'Foo' do
    let(:variable) { 'value' }
  end
end

我认为共享示例保留了它们自己的上下文,为什么这会导致问题?

您的代码中有递归:

let(:variable) { variable }

会一遍又一遍地调用自己


规范会自动传递它们的变量,所以这会起作用:

shared_examples 'Foo' do
  it_behaves_like 'Bar'
  it_behaves_like 'Baz'
end

shared_examples 'Bar' do
  it { expect(variable).to eq('value') }
end

describe SomeClass do
  let(:variable) { 'value' }
  it_behaves_like 'Foo'
end