gpt4 book ai didi

ruby-on-rails - Rspec Rails - 在请求规范中模拟远程请求

转载 作者:行者123 更新时间:2023-12-05 06:25:23 26 4
gpt4 key购买 nike

我的问题是在 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 不是本地主机。

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 ==)

最佳答案

require 'rails_helper'

RSpec.describe 'AdminWhitelistAccess', type: :request do
it 'Allow local access access to the active admin area' do
get '/admin/login'
expect(request.remote_addr).to eq('127.0.0.1')
expect(request.headers['REMOTE_ADDR']).to eq('127.0.0.1')
expect(response).to have_http_status(:ok)
end
end

RSpec.describe 'AdminWhitelistBlocked', type: :request do
before :each do
allow_any_instance_of(ActionDispatch::Request).to receive(:remote_addr).and_return('0.0.0.0')
end

it 'Allow local access access to the active admin area' do
expect { get '/admin/login' }.to raise_error(ActionController::RoutingError)
end
end

关于ruby-on-rails - Rspec Rails - 在请求规范中模拟远程请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57173769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com