如何模拟黄瓜/水豚的IP地址?
答
我解决它通过将IP地址的环境变量:
When /^the request ip address is "([^\"]*)"$/ do |ip_address|
ENV['RAILS_TEST_IP_ADDRESS'] = ip_address
end
application_controller.rb:
before_filter :mock_ip_address
def mock_ip_address
if Rails.env == 'cucumber' || Rails.env == 'test'
test_ip = ENV['RAILS_TEST_IP_ADDRESS']
unless test_ip.nil? or test_ip.empty?
request.instance_eval <<-EOS
def remote_ip
"#{test_ip}"
end
EOS
end
end
end
答
我Leventix的和Ramon的解决方案的组合:
规格/支持/ remote_ip_monkey_patch.rb
module ActionDispatch
class Request
def remote_ip_with_mocking
test_ip = ENV['RAILS_TEST_IP_ADDRESS']
unless test_ip.nil? or test_ip.empty?
return test_ip
else
return remote_ip_without_mocking
end
end
alias_method_chain :remote_ip, :mocking
end
end
+0
您能否告诉我什么样的对象'ENV ['RAILS_TEST_IP_ADDRESS']'是这样我可以创建它?它只是一个字符串?我会尝试''123.123.123.123''或什么的。 – 2014-02-04 23:56:42
我在轨道上3.1,我不得不remote_ip更改为IP。这适用于rubygeocoder.com gem。感谢发布! – jspooner 2011-09-08 16:05:35
这很酷,很有用。但是给其他读者的一个提示:最好通过像'spec/support/remote_ip_monkey_patch.rb'这样的文件打开它来打开ApplicationController。它更清洁,更漂亮。 – 2011-12-08 10:11:06