Ruby on Rails - Stub Remote IP with RSpec

11 Apr 2012

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:

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 astubbed version of theremote_ip_-method and then return a predefined ip address when that method is called.


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