public
Last active

Geocoder: Stub out address geocoding during RSpec unit tests

  • Download Gist
mock_geocoder.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
# In spec_helper:
# RSpec.configure do |config|
# ...
# config.include(MockGeocoder)
# end
#
# In your tests:
# it 'mock geocoding' do
# mock_geocoding! # You may pass additional params to override defaults (i.e. :coordinates => [10, 20])
# address = Factory(:address)
# address.lat.should eq(1)
# address.lng.should eq(2)
# end
 
require 'geocoder/results/base'
 
module MockGeocoder
def self.included(base)
base.before :each do
::Geocoder.stub(:search).and_raise(RuntimeError.new 'Use "mock_geocoding!" method in your tests.')
end
end
 
def mock_geocoding!(options = {})
options.reverse_merge!(:address => 'Address', :coordinates => [1, 2], :state => 'State', :state_code => 'State Code', :country => 'Country', :country_code => 'Country code')
 
MockResult.new.tap do |result|
result.stub options
Geocoder.stub :search => [result]
end
end
 
class MockResult < ::Geocoder::Result::Base
def initialize(data = [])
super(data)
end
end
end

Hi. I'm having a problem using this because the Geocoder::Result module isn't found.

spec/support/mock_geocoder.rb:37:in `<module:MockGeocoder>': uninitialized constant Geocoder::Result (NameError)

As far as I can tell, it's never loaded by Geocoder.

Do I need to require this file specifically? How do I do that?

@dtuite Did you ever figure it out?

@jmccartie I'm afraid not. Let me know if you get anywhere please.

@dtuite I bailed on trying to stub out the object and used FakeWeb instead.

add require 'geocoder/results/base' at the top of gist

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.