Change value of request.remote_ip in Ruby on Rails

跟風遠走 提交于 2019-11-30 12:26:20
Veger

If you want this functionality in your whole application, it might be better/easier to override the remote_ip method in your app/helpers/application_helper.rb:

class ActionDispatch::Request #rails 2: ActionController::Request
  def remote_ip
    '1.2.3.4'
  end
end

And the 1.2.3.4 address is available everywhere

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.

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

get '/', {}, { 'REMOTE_ADDR' => '1.2.3.4' }

For integration tests, this works with rails 5:

get "/path", params: { }, headers: { "REMOTE_ADDR" => "1.2.3.4" }

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

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!

This answer is only works for rails3 (I found this answer when trying to answer a similar question for rails 3),

So I will post it here in case if someone is trying to do the same thing in Rails3 env

class ActionDispatch::Request
  def remote_ip
    '1.2.3.4'
  end
end

HTH

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!