Some Guy
Some Guy

Reputation: 13588

How to mock out remote_ip in a Rspec helper?

I have a helper spec that says the following: expect(request).to receive(:remote_ip).and_return('1.2.3.4')

Running the tests, they pass, but with a warning:

WARNING: An expectation of :remote_ip was set on nil. To allow expectations on nil and suppress this message, set config.allow_expectations_on_nil to true. To disallow expectations on nil, set config.allow_expectations_on_nil to false.

I've tried using helper.request and controller.request, but then the tests fails: undefined method remote_ip for nil:NilClass

How do you mock out your ip address?

Upvotes: 12

Views: 5777

Answers (3)

Tamal Chakroborty
Tamal Chakroborty

Reputation: 71

before do
  request.env['REMOTE_ADDR'] = '59.152.62.114'
end

This will resolve your problem. However, if you have used the ip in a private method of your controller can check out this link:

Upvotes: 4

Timofey Lavnik
Timofey Lavnik

Reputation: 151

You can use env key for the method arguments that will contain "REMOTE_ADDR" key:

post path, params: params, env: { "REMOTE_ADDR": your_desired_ip }

Upvotes: 11

JanDintel
JanDintel

Reputation: 1039

Answer

You can set the remote_ip in the helper with controller.request.remote_addr = '1.2.3.4'.

Example

Helper file:

module ApplicationHelper
  def ip
    request.remote_ip
  end
end

Spec file:

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

Explanation

Helper specs mix in ActionView::TestCase::Behavior. This provides a helper object which mixes in the helper module being spec'd, along with ApplicationHelper. (In this case the module being spec'd is the ApplicationHelper).

When the helper spec is executed is sets the controller object to an ActionView::TestCase::TestController. The request object on this test controller is an ActionController::TestRequest.

Using the #remote_addr= setter on the test request, sets the "REMOTE_ADDR" key in the @env instance variable. The remote_ip uses the same "REMOTE_ADDR" key in the @env instance variable to retrieve the IP.

Upvotes: 2

Related Questions