Search code examples
ruby-on-railsrubyrspecrspec-railsrspec3

Rspec let scoping with shared examples


I'm with a problem with let and shared examples. What's happening is that my second shared_context let is overriding the first.

Example:

RSpec.shared_examples "an example" do
  include_context "a"
  include_context "b"
end

shared_context 'a' do
  let(:let_example) { p 'let_example a' }

  include_context "c"
end

shared_context 'b' do
  let(:let_example) { p 'let_example b' }

  include_context "c"
end

shared_context 'c' do
  before do
    let_example
  end
end

It's always printing let_example b.


Solution

  • Here in your example method re-defining has been done. When include_context 'a' has been executed then it defines let_example as a method which prints 'let_example a'. But when you include_context 'b' has been executed then redefines the method let_example which would effectively prints let_example 'b'.