How to Stub IP in RSpec 3?

Stub Ip With Rspec 3 Image

Often when you are writing unit tests, you want to stub your IP address. Some of the uses cases could be – you are checking if IP is within the certain range. In this quick tutorial I want to show you how to stub ip in RSpec 3.x , and how it is different from stubbing IP using RSpec 2.x.

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

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

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 stub the IP  in RSpec 3.x use this:

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

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Related Posts

Join the Discussion

Your email address will not be published. Required fields are marked *

arrow