Stub out address geocoding during RSpec unit test
Asked Answered
N

2

9

I'm using the geocoder gem to add geocoding functionality to one of my Active Record model classes. This works great, but I don't actually want the geocoding to fire during unit tests.

I've tried stubbing out the call to geocode by adding this to my RSpec test:

before(:each) do
User.stub!(:geocode).and_return([1,1]) end

However, when I run my tests it still appears to be calling out to geocode. What am I doing wrong?

FYI, this all works if I stub on the instance level (e.g. some_user.stub! instead of User.stub!).

Naissant answered 13/4, 2011 at 6:46 Comment(3)
are you using geocode in your app like user = User.first and then user.geocode?Dimpledimwit
Just fyi, another asset to geocode and display google maps: github.com/apneadiving/Google-Maps-for-RailsElviraelvis
Check out my implementation: Gist: gist.github.com/1275502 My notes: code-snippets.paveltyk.info/snippets/80Tansey
D
9

If you want to use stubbing on the instance level, you should use other mocking framework than RSpec’s. It's mocha for example (add the following to spec/spec_helper.rb):

Spec::Runner.configure do |config|
  config.mock_with :mocha
end

http://rspec.info/documentation/mocks/other_frameworks.html

Now, you can use any_instance in your tests:

before(:each) do
 User.any_instance.stub(:geocode).and_return([1,1]) 
end
Dimpledimwit answered 13/4, 2011 at 8:2 Comment(3)
This works if you only care about the return value of :geocode. But the geocoder module actually updates the latitude and longitude of the object. How would I stub that out?Gurnard
In fact, the code you gave works with RSpec >= 2.6, but not with Mocha.Diacaustic
@Gurnard a little late, but I decided to approach it like this, stubbing latitude and longitude in addition to the main geocode method: Restaurant.any_instance.stub(:geocode).and_return([1, 1]) Restaurant.any_instance.stub(:latitude).and_return(1) Restaurant.any_instance.stub(:longitude).and_return(1)Handknit
S
3

it's

before(:each) do 
  Address.any_instance.stubs(:geocode).returns([1,1])
end

with mocha.

Stercoraceous answered 8/6, 2011 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.