Lev*_*tix 4 ruby-on-rails cucumber capybara
我正在使用Cucumber和Capybara,我想要一种模拟请求IP地址的方法,如下所示:
Given the request ip address is "10.1.2.3"
Run Code Online (Sandbox Code Playgroud)
我通过在环境变量中传递IP地址来解决它:
When /^the request ip address is "([^\"]*)"$/ do |ip_address|
ENV['RAILS_TEST_IP_ADDRESS'] = ip_address
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我将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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2727 次 |
| 最近记录: |