Read more

Stub a request's IP address in a Cucumber scenario

Henning Koch
October 23, 2011Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more 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 :)

Posted by Henning Koch to makandra dev (2011-10-23 21:10)