Marcin Doliwa
Marcin Doliwa

Reputation: 3659

How to set a stub for all tests?

In controller I'm using external geocoding service with line:

loc = Location.geocode(@event.raw_location)

I'd like to set a stub for all my tests with:

allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})

Where should I put this code?

Upvotes: 2

Views: 1027

Answers (1)

byterussian
byterussian

Reputation: 3609

You should declare a global before(:each) in your rails_helper.rb or spec_helper.rb

RSpec.configure do |config|
  config.before(:each) do
    allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})
  end
end

EDIT:

Also, if you want to run this 'global' before(:each) only for the tests that involving the geocoding calls, you can write:

RSpec.configure do |config|
  config.before(:each, geocoding_mock: true) do
    allow(Location).to receive(:geocode).with(nil).and_return({city: nil, state: nil, country: nil})
  end
end

then in your tests:

describe Location, geocoding_mock: true do
...
end

Upvotes: 6

Related Questions