Skip to main content

Ruby on Rails - Stub Remote IP with RSpec

·141 words·1 min
Ruby
Author
Dennis Schneider
Table of Contents

Today I wanted to simulate an external IP request with RSpec (2.8.0) and Rails (3.1). Unfortunately Google didn’t reveal much upon a search. So I came up with this solution:

ActionDispatch::Request.any_instance.stub(:remote_ip).and_return("192.168.0.1")

The ActionDispatch module holds the Request class which contains information about the HTTP request, like the request body, authorization etc. It also contains a method for obtaining the associated ip address obtained by the remote ip middleware.

As I haven’t had access to the request object, I used_ any_instance to tell RSpec that literally any derived instance from that class should get a stubbed version of the remote_ip_-method and then return a predefined ip address when that method is called.

UPDATE
#

I also figured out that you can achieve that behavior by simply specifying another parameter when making a request via RSpec:

xhr :post, PATH, DATA, "REMOTE_ADDR" => "192.168.0.1"