Search code examples
ruby-on-railsrspecrspec-railsruby-on-rails-5rspec3

RSpec 3.5 pass argument to shared_context


I have this code that I want to reuse in several specs:

RSpec.shared_context "a UserWorker" do |user|

  let(:mock_context_user) {{
    id: 1,
    brand: user.brand,
    backend_token: user.backend_token
  }}

  before(:each) do
    allow(SomeClass).to receive(:some_method)
      .with(user.id).and_return(mock_context_user)
  end

  before(:each, context: true) do
    Sidekiq::Testing.inline!
  end

  after(:each, context: true) do
    Sidekiq::Testing.fake!
  end

end

And in the spec file that uses the shared code:

let(:user) { build :user } # FactoryGirl

...

describe '#perform' do
  # some lets here

  include_context 'a UserWorker', user

  context 'when something exists' do
    it 'does some stuff' do
      # test some stuff here
    end
  end
end

But that gives me this error:

/.rvm/gems/ruby-2.3.0@fb-cont/gems/rspec-core-3.5.1/lib/rspec/core/example_group.rb:724:in `method_missing': `user` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). (RSpec::Core::ExampleGroup::WrongScopeError)

Suggestions? Any help is appreciated.


Solution

  • Since it will always return the same mock_context_user, you can try something more generic like:

    allow(SomeClass)
     .to receive(:some_method)
     .with(an_instance_of(Fixnum))
     .and_return(mock_context_user)
    

    But I'm not actually sure if an_instance_of is available for RSpec 3.5, it is on RSpec 3.3.