Stub a request's IP address in a Cucumber scenario

Updated . Posted . Visible to the public.

The solution in this card is based on a stack overflow post Show archive.org snapshot by Leventix Show archive.org snapshot .

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:

Given my IP address is 188.174.117.205

Rails 3

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:

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:

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 :)

Profile picture of Henning Koch
Henning Koch
Last edit
Keywords
capybara
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-10-23 19:10)