The Geocoder gem allows for stubbing while testing: https://github.com/alexreisner/geocoder#testing
Testing
When writing tests for an app that uses Geocoder it may be useful to avoid network calls and have Geocoder return consistent, configurable results. To do this, configure the :test lookup and/or :ip_lookup
Geocoder.configure(lookup: :test, ip_lookup: :test)
Add stubs to define the results that will be returned:
Geocoder::Lookup::Test.add_stub(
"New York, NY", [
{
'coordinates' => [40.7143528, -74.0059731],
'address' => 'New York, NY, USA',
'state' => 'New York',
'state_code' => 'NY',
'country' => 'United States',
'country_code' => 'US'
}
]
)
This works when calling the service without specifying a service:
results = Geocoder.search(self.address)
But when I specify a service directly in the call, the stubbing doesn't happen. Is there a way to stub this type of call?
results = Geocoder.search(self.address, lookup: :google)
I am new to ruby and rails and would appreciate any help.
There's a small mistake in the example code. Should be Geocoder.search(self.address, lookup: :google)
. Only mentioning it as it threw me off initially.
After reading through the source code it's clear that stubbing and specifying a service cannot work together.
name = options[:lookup] || Configuration.lookup || Geocoder::Lookup.street_services.first
This is code is from the Query class when it determines the service to be used. You can see that it checks for a passed lookup service option first, then it checks the configuration (which has been set to test), then it goes with a default service which is just the first one on the list.
The easiest solution is using the VCR (and Webmock) gem. It records the results from a live network request into a file and responds with the file contents for all future requests by the test. Stops live network requests and spares you from having to create mock data.