Search code examples
ruby-on-railsrspecrspec-rails

Rspec Rails - Mocking remote requests in requests spec


My problem is mocking the IP in an Rspec request spec. I want to mock a request from a remote (non-localhost) request. This is to test some route constraints.

Here is my spec so far:

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

I expect the remote IP to not be 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 ==)

UPDATE:

I have also tried setting the request's remote address beforehand:

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

However, still no success:

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


Solution

  • 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