Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 717
Some Guy Avatar asked May 10 '16 18:05

Some Guy


2 Answers

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 }
like image 60
Timofey Lavnik Avatar answered Oct 24 '22 19:10

Timofey Lavnik


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:

like image 31
Tamal Chakroborty Avatar answered Oct 24 '22 18:10

Tamal Chakroborty