【发布时间】:2019-07-24 00:31:08
【问题描述】:
我的问题是在 Rspec 请求规范中模拟 IP。我想模拟来自远程(非本地主机)请求的请求。这是为了测试一些路由约束。
这是我目前的规格:
require 'rails_helper'
RSpec.describe 'AdminWhitelistBlocked', type: :request do
before :each do
RSpec.configure do |config|
config.before(:each, allow_rescue: true) do
Rails.application.config.action_dispatch.stub(:show_exceptions) { true }
Rails.application.config.stub(:consider_all_requests_local) { false }
end
end
end
it 'Allow local access access to the active admin area' do
get '/admin/login'
expect(request.remote_ip).to eq('0.0.0.0')
expect(request.headers['REMOTE_ADDR']).to eq('0.0.0.0')
expect(response).to have_http_status(:not_found)
end
end
我希望远程 IP 不是 localhost。
Failures:
1) AdminWhitelistBlocked Allow local access access to the active admin area
Failure/Error: expect(request.remote_ip).to eq('0.0.0.0')
expected: "0.0.0.0"
got: "127.0.0.1"
(compared using ==)
更新:
我也尝试过预先设置请求的远程地址:
require 'rails_helper'
RSpec.describe 'AdminWhitelistBlocked', type: :request do
before :each do
RSpec.configure do |config|
config.before(:each, allow_rescue: true) do
@request.remote_addr = '0.0.0.0'
end
end
end
it 'Allow local access access to the active admin area' do
get '/admin/login'
expect(request.remote_addr).to eq('0.0.0.0')
expect(request.headers['REMOTE_ADDR']).to eq('0.0.0.0')
expect(response).to have_http_status(:not_found)
end
end
但是还是没有成功:
Failures:
1) AdminWhitelistBlocked Allow local access access to the active admin area
Failure/Error: expect(request.remote_addr).to eq('0.0.0.0')
expected: "0.0.0.0"
got: "127.0.0.1"
(compared using ==)
【问题讨论】:
-
你可以试试 webmock gem,它应该可以简化这些类型的测试。以下是设置获取请求期望的示例:expect(a_request(:get, "0.0.0.0").with(query: {"a" => ["b", "c"]}))。 to have_been_made
标签: ruby-on-rails rspec rspec-rails