Som*_*Guy 6 ruby rspec ruby-on-rails
我有一个辅助规范,上面写着:
expect(request).to receive(:remote_ip).and_return('1.2.3.4')
运行测试,他们通过了,但有一个警告:
警告:对 的期望:remote_ip设置为nil。要允许预期nil并禁止此消息,请设置config.allow_expectations_on_nil为true。要禁止对 的期望nil,请设置config.allow_expectations_on_nil为false。
我试过使用 helper.request 和 controller.request,但是测试失败了: undefined method remote_ip for nil:NilClass
你如何模拟你的IP地址?
小智 11
您可以将 env key 用于将包含 key 的方法参数"REMOTE_ADDR":
post path, params: params, env: { "REMOTE_ADDR": your_desired_ip }
Run Code Online (Sandbox Code Playgroud)
小智 2
remote_ip您可以在助手中使用进行设置controller.request.remote_addr = '1.2.3.4'。
例子
帮助文件:
module ApplicationHelper
def ip
request.remote_ip
end
end
Run Code Online (Sandbox Code Playgroud)
规格文件:
require 'rails_helper'
RSpec.describe ApplicationHelper, type: :helper do
describe '#ip' do
it 'returns the IP' do
controller.request.remote_addr = '1.2.3.4'
expect(helper.ip).to eql '1.2.3.4'
end
end
end
Run Code Online (Sandbox Code Playgroud)
辅助规格混合在一起ActionView::TestCase::Behavior。这提供了一个helper对象,该对象与指定的帮助器模块以及ApplicationHelper. (在这种情况下,指定的模块是ApplicationHelper)。
当执行辅助规范时,会将controller对象设置为ActionView::TestCase::TestController. request该测试控制器上的对象是一个ActionController::TestRequest.
#remote_addr=在测试请求上使用setter,设置实例变量"REMOTE_ADDR"中的键@env。使用实例变量中的remote_ip相同键来检索 IP。"REMOTE_ADDR"@env