My answer not for everyone since I wanted to test request.location
locally only. But if you want to do the same then I have the solution for you. First of all, let me show you source code for .location
method:
module Geocoder
module Request
def location
@location ||= begin
detected_ip = env['HTTP_X_REAL_IP'] || (
env['HTTP_X_FORWARDED_FOR'] &&
env['HTTP_X_FORWARDED_FOR'].split(",").first.strip
)
detected_ip = IpAddress.new(detected_ip.to_s)
if detected_ip.valid? and !detected_ip.loopback?
real_ip = detected_ip.to_s
else
real_ip = self.ip
end
Geocoder.search(real_ip).first
end
@location
end
end
end
# ...
As you can see, there is variable detected_ip
and to find it's data gem checks out env['HTTP_X_REAL_IP']
. Well, now we can easily stub that in our controller:
class HomeController < ApplicationController
def index
env['HTTP_X_REAL_IP'] = '1.2.3.4' if Rails.env.development?
location = request.location
# => #<Geocoder::Result::Freegeoip:0x007fe695394da0 @data={"ip"=>"1.2.3.4", "country_code"=>"AU", "country_name"=>"Australia", "region_code"=>"", "region_name"=>"", "city"=>"", "zipcode"=>"", "latitude"=>-27, "longitude"=>133, "metro_code"=>"", "area_code"=>""}, @cache_hit=nil>
end
end
It works with geocoder '1.2.5' (can't promise that it works with earlier versions - you need check out source code for that or bump the gem).