在Ruby on Rails中更改request.remote_ip的值

出于测试目的,我想更改request.remote_ip的返回值。 在我的开发机器上,它总是返回127.0.0.1,但我想给自己不同的假IP来测试我的应用程序的正确行为,而不首先将它部署到实时服务器!

谢谢。

如果您希望在整个应用程序中使用此function,则可能更好/更容易覆盖app/helpers/application_helper.rb的remote_ip方法:

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

并且1.2.3.4地址随处可用

您可以通过在测试环境中为remote_ip值创建一个mutator来作弊,这通常是未定义的。

例如,使用以下内容更改test / test_helper.rb中的类:

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

然后,在测试期间,您可以根据需要重新分配:

 def test_something @request.remote_ip = '1.2.3.4' end 

这可以在单独的测试中完成,也可以在您的设置例程中,在适当的地方完成。

在编写validationIP禁止,地理定位等的function测试之前,我不得不使用它。

您可以使用以下命令修改请求对象:

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

request.remote_ip现在返回1.2.3.4

我现在最终做的是将这些代码放在config/environments/development.rb文件的末尾,以确保它只在开发时执行

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

因此,当服务器启动时,这会将remote_ip设置为1.2.3.4。 每次更改值时都必须重新启动服务器!

rails 4.0.1 rc。 经过一小时的搜索,在挖掘代码时找到了这个简单的解决方案:)

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

对于集成测试,这适用于rails 5:

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

这个答案只适用于rails3(我在尝试回答rails 3的类似问题时找到了这个答案),

所以如果有人试图在Rails3环境中做同样的事情,我会在这里发布

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

HTH