1

I'm making use of the geokit-rails gem to perform geolocation based on the IP address of the user who is logging in via #geocode_ip_address (https://github.com/geokit/geokit-rails#ip-geocoding-helper).

However, I'm having a very hard time finding a way to test this via the Rails 5 IntegrationTest. I need a way to provide multiple remote IP addresses when simulating a login but I am stuck on the following issues:

  • how to spoof an IP address (that will vary based on the user logging in)
  • how to prevent making a ton of requests to the geolocation service

My original approach was to just skip it and place the :geo_location information in the session hash, however this seems to have gone away in Rails 5 per https://github.com/rails/rails/issues/23386.

Anybody have experience with a similar set-up?

krsyoung
  • 1,171
  • 1
  • 12
  • 24

1 Answers1

2

As per implementation of the ip lookup in geokit-rails https://github.com/geokit/geokit-rails/blob/master/lib/geokit-rails/ip_geocode_lookup.rb#L44 you could simply stub the remote_ip method on the request object.

Once geokit-rails found a geo_location based on your IP it stores it as a geo_location object in the session. You might not want this "caching" behaviour in development/test, so I am deleting the object right before spoofing the IP.

Here an example implementation:

class SomeController < ApplicationController
  prepend_before_action :spoof_remote_ip if: -> { %w(development test).include? Rails.env }
  geocode_ip_address

  def index
    @current_location = session[:geo_location]
  end

  def spoof_remote_ip
    session.delete(:geo_location) if session[:geo_location]
    request.env["action_dispatch.remote_ip"] = ENV['SPOOFED_REMOTE_ADDR']
  end
end
# .env
SPOOFED_REMOTE_ADDR = "xx.xxx.xx.xxx"
Robin
  • 866
  • 7
  • 19
  • Thanks @Robin, looks like that could help with "how to spoof an IP address". Any chance you have an example / have you actually implemented this? – krsyoung Aug 03 '19 at 16:06
  • 1
    @krsyoung A few days later I added an example to my answer. Only took me 2 years to let you know :D – Robin Aug 04 '21 at 09:35