How to stub an IP in Ruby on Rails, RSpec Version 3 ?

Often when you are writing unit tests, you want to mock your IP address. Some of the uses cases could be – you are checking if IP is within the certain range.

For RSpec 2.x  mocking  IP would look like this:


Taken from here

However, if you try to do it in RSpec 3.x, it will give you an error since ‘any_instance‘ syntax is deprecated.

To make the same work for RSpec 3.x use this:

   allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("")

About Anatoly Spektor

My name is Anatoly Spektor (originally Anatolijs Spektors) I am Software and Web Developer. I have worked in Seneca Center for Development of Open Technology on Big Blue Button Add-on - Polling Module, Red Hat and some other places :) I am an author of the book 'Eclipse Debugging How To', Muay Thai fighter and amateur photographer ;)
This entry was posted in Programming Languages and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s