1

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.

Nick
  • 423
  • 7
  • 17
  • Also opened issue asking here: https://github.com/alexreisner/geocoder/issues/1497 – Nick Mar 27 '21 at 14:19
  • I would assume the `:google` service would be defined in some config like `application.rb`, and not every time you make a `search`. See https://github.com/alexreisner/geocoder#geocoding-service-lookup-configuration Maybe try that instead? – max pleaner Mar 27 '21 at 16:52
  • @maxpleaner The reason I have to specify it in the search is that we have multiple services defined (google, mapquest, etc), and if google fails, we will try the next service by calling it passing in the :mapquest symbol. – Nick Mar 27 '21 at 17:38
  • 1
    Well, you can always write the stubs in the normal fashion if you need to: `expect(Geocoder).to receive(search).with().and_return()`. – max pleaner Mar 27 '21 at 19:46

1 Answers1

1

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.

https://github.com/vcr/vcr

stevenpcc
  • 36
  • 3