Search code examples
ruby-on-railsrspecrails-geocoder

Rails Rspec and Geocoder IP lookup


Geocoder DOCS explain how to fake a Geocoder lookup with Street addresses, but it doesn't seem to work with IP addresses.

This is my spec/support/geocoder.rb

Geocoder.configure(:lookup => :test)

Geocoder::Lookup::Test.add_stub(
  "1.1.1.1", [
  {
    'latitude'     => 10,
    'longitude'    => 10,
    'address'      => 'Test Address',
    'state'        => 'Test State',
    'state_code'   => 'TS',
    'country'      => 'Test Country',
    'country_code' => 'TC'
  }
]
)

Geocoder::Lookup::Test.set_default_stub(
  [
    {
      'latitude'     => 10,
      'longitude'    => 10,
      'address'      => 'Test Address',
      'state'        => 'Test State',
      'state_code'   => 'TS',
      'country'      => 'Test Country',
      'country_code' => 'TC'
    }
  ]
)

this is my service:

if params[:ip]
  lat = Geocoder.search(params[:ip])[0].latitude
  lng = Geocoder.search(params[:ip])[0].longitude
  venues = venues.near([lat, lng], APP_CONFIG['geo_location_radius'], order: 'average_rating DESC')
end

And this is my service spec:

context "find featured venues by ip" do
  let(:params) do
    {
      date:     Date.today,
      featured: true,
      ip:       '1.1.1.1',
    }
  end

  it do
    aggregate_failures do
      expect(raw_venues.map { |v| v.id }.sort).to eq [venue1.id]
    end
  end

end

If I enter with pry in the it block and I try Geocoder.search('1.1.1.1') I get a "real" object response with a location in Australia instead of my stub, while I correctly get my stub if I enter something like Geocoder.search('Florence, Italy') ..

How can I setup stub responses to work with IP lookup?


Solution

  • Solution is simply:

    Geocoder.configure(ip_lookup: :test)