【问题标题】:Rails 5 IntegrationTest with IP GeolocationRails 5 IntegrationTest 与 IP 地理定位
【发布时间】:2017-02-09 02:32:29
【问题描述】:

我正在使用geokit-rails gem 根据通过#geocode_ip_address (https://github.com/geokit/geokit-rails#ip-geocoding-helper) 登录的用户的IP 地址执行地理定位。

但是,我很难找到一种通过 Rails 5 IntegrationTest 进行测试的方法。我需要一种在模拟登录时提供多个远程 IP 地址的方法,但我遇到了以下问题:

  • 如何欺骗 IP 地址(取决于登录的用户)
  • 如何防止向地理定位服务发出大量请求

我最初的方法是跳过它并将:geo_location 信息放在session 哈希中,但是这似乎在Rails 5 per https://github.com/rails/rails/issues/23386 中消失了。

有人有类似设置的经验吗?

【问题讨论】:

  • 你在使用 RSpec 吗?
  • 测试用例使用的是内置Minitest。

标签: ruby-on-rails geolocation integration-testing ruby-on-rails-5 geokit


【解决方案1】:

根据在geokit-rails https://github.com/geokit/geokit-rails/blob/master/lib/geokit-rails/ip_geocode_lookup.rb#L44 中的ip 查找实现,您可以简单地在request 对象上存根remote_ip 方法。

一旦 geokit-rails 根据您的 IP 找到 geo_location,它会将其作为 geo_location 对象存储在 session 中。您可能不希望在开发/测试中出现这种“缓存”行为,因此我将在欺骗 IP 之前删除该对象。

这里是一个示例实现:

class SomeController < ApplicationController
  prepend_before_action :spoof_remote_ip if: -> { %w(development test).include? Rails.env }
  geocode_ip_address

  def index
    @current_location = session[:geo_location]
  end

  def spoof_remote_ip
    session.delete(:geo_location) if session[:geo_location]
    request.env["action_dispatch.remote_ip"] = ENV['SPOOFED_REMOTE_ADDR']
  end
end
# .env
SPOOFED_REMOTE_ADDR = "xx.xxx.xx.xxx"

【讨论】:

  • 谢谢@Robin,看起来这可以帮助解决“如何欺骗 IP 地址”。有没有机会你有一个例子/你真的实现了这个吗?
  • @krsyoung 几天后,我在答案中添加了一个示例。只花了我 2 年的时间让你知道 :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
相关资源
最近更新 更多