【问题标题】:Rspec Rails - Mocking remote requests in requests specRspec Rails - 在请求规范中模拟远程请求
【发布时间】: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


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多