I am trying to set up my RSpec tests to use stubs rather then using networking to do the geocoding.
I added this:
before(:each) do
Geocoder.configure(:lookup => :test)
Geocoder::Lookup::Test.add_stub(
"Los Angeles, CA", [{
:latitude => 34.052363,
:longitude => -118.256551,
:address => 'Los Angeles, CA, USA',
:state => 'California',
:state_code => 'CA',
:country => 'United States',
:country_code => 'US'
}],
)
end
I am using FactoryGirl to create the test data like so:
FactoryGirl.define do
factory :market do
city 'Los Angeles'
state 'CA'
radius 20.0
end
end
The latitude/longitude are correctly being geocoded and stored in latitude/longitude. However, when I try:
Market.near(params[:search])
it returns nil.. But, if I just use the lookup => :google it works just as I intend it to. Has anyone got this working before, specifically the near method of geocoder?
I ended up coming back to this on a new project and figured it out.
The docs on geocoder actually state that the hash has to have string keys and not symbols. geocoder docs - see notes
i.e.
before(:each) do
Geocoder.configure(:lookup => :test)
Geocoder::Lookup::Test.add_stub(
"Los Angeles, CA", [{
"latitude" => 34.052363,
"longitude" => -118.256551,
"address" => 'Los Angeles, CA, USA',
"state" => 'California',
"state_code" => 'CA',
"country" => 'United States',
"country_code" => 'US'
}],
)
end
and not how I did it in the original post:
i.e. :latitude => 34.052363
I ended up doing something a bit more dynamic:
# frozen_string_literal: true
module GeocoderStub
def self.stub_with(facility)
Geocoder.configure(lookup: :test)
results = [
{
'latitude' => Faker::Address.latitude.first(9),
'longitude' => Faker::Address.longitude.first(9)
}
]
queries = [facility.full_address, facility.zip]
queries.each { |q| Geocoder::Lookup::Test.add_stub(q, results) }
end
end
and in my factory:
require './spec/support/geocoder_stub'
FactoryGirl.define do
factory :facility do
name { Faker::Company.name }
rating { rand(1..5) }
street { Faker::Address.street_address }
city { Faker::Address.city }
state { Faker::Address.state }
zip { Faker::Address.zip_code }
after(:build) { |facility| GeocoderStub.stub_with(facility) }
end
end
This adds a geocoder stub for every Facility factory that is built for both full address (method defined in facility) and zip.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With