Cannot get shared_contexts to work in rspec 3.9.0 / rspec-rails 4

759 views Asked by At

In previous versions of rspec, I could do something like:

spec/models/test_spec.rb

require 'rails_helper'

describe 'something', :foobar do
  it 'does not seem to be working' do
    puts lol
  end
end

spec/support/foobar.rb

shared_context 'foobar', :foobar do
  let(:lol) { 'haha' }
end

spec/rails_helper.rb

...
RSpec.configure do |config|
  Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
end

This would work fine, my specs would have access to whatever methods/lets were defined in the shared context... However, when upgrading to rspec-rails 4, this now results in:

 Failure/Error: puts lol

 NameError:
   undefined local variable or method `lol' for #<RSpec::ExampleGroups::...

Rspec's latest documentation says:

We've also added a config option that lets you determine how shared context metadata is treated:

RSpec.configure do |config| config.shared_context_metadata_behavior = :trigger_inclusion # or config.shared_context_metadata_behavior = :apply_to_host_groups end The former value (:trigger_inclusion) is the default and exists only for backwards compatibility. It treats metadata passed to RSpec.shared_context exactly how it was treated in RSpec 3.4 and before: it triggers inclusion in groups with matching metadata. We plan to remove support for it in RSpec 4.

The latter value (:apply_to_host_groups) opts-in to the new behavior. Instead of triggering inclusion in groups with matching metadata, it applies the metadata to host groups. For example, you could focus on all groups that use the DB by tagging your shared context:

RSpec.shared_context "DB support", :focus do # ... end

However, after reading that over 5 times, I still have no idea what "apply_to_host_groups" actually means. What is a host group ??? Regardless, setting that configuration option doesn't fix this problem.

I have verified my file in spec/support is being loaded, but for whatever reason, lets/methods defined are not available in the example group using the shared context metadata tag. What am I doing wrong?

1

There are 1 answers

2
Samuel-Zacharie Faure On

Here is the correct syntax.

In your config file:

  config.include_context 'with that context', type: :foobar

Your test:

describe 'something', type: :foobar do
  it 'does not seem to be working' do
    puts lol
  end
end

Your shared tests:

RSpec.shared_context 'with that context' do
  # Tests go here
end