Rspec-core: Shared context doesn't work with extended methods

Created on 16 Dec 2019  ·  5Comments  ·  Source: rspec/rspec-core

Subject of the issue

Methods that were injected via config.extend(...) are not defined when called within shared contexts.

Your environment

  • Ruby version: 2.6
  • rspec-core version: 3.9.0

Steps to reproduce

module Foo
  def something
    puts 'hi'
  end
end

RSpec.configure do |config|
  config.extend(Foo)
end

RSpec.shared_context 'shared' do
  something
end

Expected behavior

Prints 'hi'

Actual behavior

something is undefined

Bug

All 5 comments

Can you please provide a bit more context of how you use that shared context? I'm not able to reproduce this behavior:

module Foo
  def something
    puts 'hi'
  end
end

RSpec.configure do |config|
  config.extend Foo
end

RSpec.shared_context 'shared' do
  something
end

RSpec.describe do
  include_context 'shared'

  it { }
end

outputs:

$ rspec spec/a_spec.rb
hi
Run options: exclude {:ruby=>#<Proc:./spec/spec_helper.rb:99>}

Randomized with seed 10987


  example at ./spec/a_spec.rb:18

Finished in 0.00185 seconds (files took 1.19 seconds to load)
1 example, 0 failures

Randomized with seed 10987

I'll close this out for now and investigate what's wrong on my end then. Thanks for the response. Will report back when I figure it out.

I think the problem happens when include context inside configure block:

module Foo
  def something
    puts 'hi'
  end
end

RSpec.configure do |config|
  config.extend Foo
end

RSpec.shared_context 'shared' do
  something
end

RSpec.configure do |config|
  config.include_context 'shared', foo: :enabled
end

RSpec.describe "Foo", foo: :enabled do
  it { }
end

outputs:

$ rspec spec/foo_spec.rb
An error occurred while loading ./spec/foo_spec.rb.
Failure/Error: something

NameError:
  undefined local variable or method `something' for RSpec::ExampleGroups::Foo:Class

No examples found.

Finished in 0.00017 seconds (files took 1.35 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

@pirj I’ve reopened the issue since @tubaxenor provided the failing example.

Thanks for the reproduction example.
I suspect that it's the inclusion order. Quick debug points at lib/rspec/core/configuration.rb:1513.

It makes sense to extend first, and include after. Can you think of a good example when a module would need something that is defined in the shared context?

You can try with swapping the lines 1513 and 1514 and see if some specs/features fail.

Do you want to carefully tackle the problem?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fimmtiu picture fimmtiu  ·  3Comments

phuongnd08 picture phuongnd08  ·  5Comments

andyl picture andyl  ·  6Comments

ankit8898 picture ankit8898  ·  3Comments

wwood picture wwood  ·  5Comments