Posted about 9 years ago. Visible to the public. Linked content.

Stub a request's IP address in a Cucumber scenario

The solution in this card is based on a stack overflow post by Leventix.

If you need to make request come from a fixed IP address for the duration of a Cucumber scenario, the code below lets you write this:

Copy
Given my IP address is 188.174.117.205

Rails 3

Copy
Given /^my IP address is "(.*?)"$/ do |ip| ActionDispatch::Request.any_instance.stub(:remote_ip).and_return(ip) end

Rails 2

You will need the following step definitions:

Copy
Given /^my IP address is (\d+\.\d+\.\d+\.\d+)$/ do |ip| ApplicationController.stubbed_request_ip = ip end After do ApplicationController.stubbed_request_ip = nil end

You will also need to add the following code to your ApplicationController:

Copy
class ApplicationController < ActionController::Base before_filter :stub_request_ip cattr_accessor :stubbed_request_ip ... private def stub_request_ip if stubbed_ip = self.class.stubbed_request_ip request.instance_eval <<-EOS def remote_ip '#{stubbed_ip}' end EOS end end end

Please do not waste time to replace the string programming above, I already went there and came back :)

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Henning Koch
Last edit:
over 6 years ago
Keywords:
capybara
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more