o_o_o--
o_o_o--

Reputation: 1025

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

Basically, I have a bunch of shared examples. I thought this would work, but I'm getting stack level too deep on the variable that's being passed.

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

the spec:

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

I thought shared examples kept their own context, why is this causing an issue?

Upvotes: 1

Views: 1142

Answers (1)

mhutter
mhutter

Reputation: 2916

You have recursion in your code:

let(:variable) { variable }

will call itself over and over again


Specs will pass down their variables automatically, so this will work:

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

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

and

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

Upvotes: 1

Related Questions