在 Ruby on Rails 中更改 request.remote_ip 的值
出于测试目的,我想更改 request.remote_ip 的返回值。在我的开发机器上时,它总是返回 127.0.0.1,因为它应该是这样,但我想给自己提供不同的假 IP 来测试我的应用程序的正确行为,而无需先将其部署到实时服务器!
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您希望在整个应用程序中使用此功能,那么覆盖
app/helpers/application_helper.rb
中的remote_ip 方法可能会更好/更容易:并且 1.2.3.4 地址随处可用
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
:And the 1.2.3.4 address is available everywhere
对于集成测试,这适用于 Rails 5:
For integration tests, this works with rails 5:
您可以使用以下方法修改请求对象:
request.remote_ip
现在返回 1.2.3.4You can modify the request object using:
request.remote_ip
now returns 1.2.3.4您可以通过在测试环境中为通常未定义的remote_ip 值创建一个变元来进行一些欺骗。
例如,使用以下内容更改 test/test_helper.rb 内部的类:
然后,在测试期间,您可以根据需要重新分配:
这可以在单独的测试中完成,也可以在您的设置例程中完成,只要合适即可。
我之前在编写验证 IP 禁止、地理位置等的功能测试时必须使用它。
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:
Then, during your testing you can reassign as required:
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。经过一个小时的搜索,在挖掘代码时发现了这个简单的解决方案:)
rails 4.0.1 rc. After hour of searching found this simple solution while digging to code :)
我现在最终要做的就是将此代码放在 config/environments/development.rb 文件的末尾,以确保它仅在开发过程中执行,
因此,当服务器启动。每次更改该值都必须重新启动服务器!
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 developmentSo this sets remote_ip to 1.2.3.4 when the server starts. Everytime you change the value you have to restart the server!
这个答案仅适用于rails3(我在尝试回答rails 3的类似问题时发现了这个答案),
所以我将把它发布在这里,以防有人试图在Rails3 env
HTH中做同样的事情
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
HTH
使用带有 Rspec 的 Rails7,我可以通过将以下
before
部分添加到我的测试请求:为了在上下文中更多地了解这一点,整个请求变为:
然后,在我的
Foo
控制器status
方法内,request.remote_ip
返回测试中分配的任何值。Using Rails7 with Rspec, I was able to change the value of
request.remote_ip
to return1.2.3.4
by adding the followingbefore
section to my test request:To see this more in context, the whole request becomes:
Then, inside of my
Foo
controllersstatus
method,request.remote_ip
returns whatever value assigned in the test.