Faking an IP with Webrat
Lately I have been diving into TDD, and more specifically BDD, thanks to the wonderful Cucumber testing framework.
Today I have had to test a specifical IP based feature. Simply put, I get the user IP and store it into the database.
The simple rails way to get a visitor IP address is
request.remote_ip
If you do this while developing you’ll usually get a predictable
127.0.0.1
How do I test that my controller puts a correct IP in the database?
At first I thought about creating a mock request object. But this way I would be testing only the saving portion of the method, not the part detecting the IP. In other words, I needed to simulate an IP address at a lower layer.
Webrat to the rescue! Thanks to the nice folks at the webrat irc channel I got an answer. Simply:
header('REMOTE_ADDR', ip_address)
The Webrat headermethod lets you set all the header variable of you session. Handy, isn’t it?