如何在 cucumber/capybara 中模拟 IP 地址?

发布于 2024-09-04 21:42:40 字数 126 浏览 2 评论 0原文

我正在使用 Cucumber 和 Capybara,我想要一种模拟请求 IP 地址的方法,如下所示:

Given the request ip address is "10.1.2.3"

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝戈者 2024-09-11 21:42:40

我通过在环境变量中传递IP地址解决了这个问题:

  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

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
尬尬 2024-09-11 21:42:40

我的 Leventix 和 Ramon 解决方案的组合:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文