Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of request.remote_ip in Ruby on Rails

For test purposes I want to change the return value of request.remote_ip. While being on my development machine it returns always 127.0.0.1 as it should but I would like to give myself different fake IPs to test the correct behavior of my app without deploying it to an live server first!

Thank you.

like image 542
Matt Avatar asked Jan 08 '10 17:01

Matt


5 Answers

You can modify the request object using:

request = ActionController::Request.new('REMOTE_ADDR' => '1.2.3.4')

request.remote_ip now returns 1.2.3.4

like image 138
Veger Avatar answered Nov 06 '22 19:11

Veger


You can cheat a bit by making a mutator for the remote_ip value in the test environment which is normally not defined.

For instance, alter the class inside of test/test_helper.rb with the following:

class ActionController::TestRequest
  def remote_ip=(value)
    @env['REMOTE_ADDR'] = value.to_s
  end
end

Then, during your testing you can reassign as required:

def test_something
  @request.remote_ip = '1.2.3.4'
end

This can be done either in the individual test, or within your setup routine, wherever is appropriate.

I have had to use this before when writing functional tests that verify IP banning, geolocation, etc.

like image 40
tadman Avatar answered Nov 06 '22 18:11

tadman


rails 4.0.1 rc. After hour of searching found this simple solution while digging to code :)

get '/', {}, { 'REMOTE_ADDR' => '1.2.3.4' }
like image 35
woto Avatar answered Nov 06 '22 20:11

woto


For integration tests, this works with rails 5:

get "/path", params: { }, headers: { "REMOTE_ADDR" => "1.2.3.4" }
like image 5
Simon Duncombe Avatar answered Nov 06 '22 18:11

Simon Duncombe


What I ended up doing now was to put this code in the end of the config/environments/development.rb file to make sure it's only executed while in development

# fake IP for manuel testing
class ActionController::Request
  def remote_ip
    "1.2.3.4"
  end
end

So this sets remote_ip to 1.2.3.4 when the server starts. Everytime you change the value you have to restart the server!

like image 3
Matt Avatar answered Nov 06 '22 18:11

Matt