Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock an IP address in cucumber/capybara?

I'm using Cucumber and Capybara and I'd like a way to simulate the request IP address, like this:

Given the request ip address is "10.1.2.3"
like image 982
Leventix Avatar asked Dec 12 '22 21:12

Leventix


2 Answers

I solved it by passing the IP address in an environment variable:

  When /^the request ip address is "([^\"]*)"$/ do |ip_address|
    ENV['RAILS_TEST_IP_ADDRESS'] = ip_address
  end

application_controller.rb:

  before_filter :mock_ip_address

  def mock_ip_address
    if Rails.env == 'cucumber' || Rails.env == 'test'
      test_ip = ENV['RAILS_TEST_IP_ADDRESS']
      unless test_ip.nil? or test_ip.empty?
        request.instance_eval <<-EOS
          def remote_ip
            "#{test_ip}"
          end
        EOS
      end
    end
  end
like image 189
Leventix Avatar answered Jan 05 '23 11:01

Leventix


My mix of Leventix's and Ramon's solutions:

spec/support/remote_ip_monkey_patch.rb

module ActionDispatch
  class Request

    def remote_ip_with_mocking
      test_ip = ENV['RAILS_TEST_IP_ADDRESS']

      unless test_ip.nil? or test_ip.empty?
        return test_ip
      else
        return remote_ip_without_mocking
      end
    end

    alias_method_chain :remote_ip, :mocking

  end
end
like image 28
Laurynas Avatar answered Jan 05 '23 12:01

Laurynas