Created
October 10, 2011 14:48
-
-
Save paveltyk/1275502 to your computer and use it in GitHub Desktop.
Geocoder: Stub out address geocoding during RSpec unit tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
@dtuite I bailed on trying to stub out the object and used FakeWeb instead.
@jmccartie Try this if you like: http://dtuite.github.com/how-to-test-the-geocoder-gem.html
add require 'geocoder/results/base'
at the top of gist
For anyone using Rspec 2+, I made a fork that works with the new expect
syntax.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jmccartie I'm afraid not. Let me know if you get anywhere please.