Change value of request.remote_ip in Ruby on Rails

2019-02-08 19:56发布

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.

7条回答
该账号已被封号
2楼-- · 2019-02-08 20:30

For integration tests, this works with rails 5:

get "/path", params: { }, headers: { "REMOTE_ADDR" => "1.2.3.4" }
查看更多
贪生不怕死
3楼-- · 2019-02-08 20:35

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

get '/', {}, { 'REMOTE_ADDR' => '1.2.3.4' }
查看更多
小情绪 Triste *
4楼-- · 2019-02-08 20:37

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

查看更多
该账号已被封号
5楼-- · 2019-02-08 20:53

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

查看更多
可以哭但决不认输i
6楼-- · 2019-02-08 20:54

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!

查看更多
倾城 Initia
7楼-- · 2019-02-08 20:54

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

查看更多
登录 后发表回答