首页 > 解决方案 > 调用特定服务时如何在 ruby​​ Geocoder 中存根调用

问题描述

Geocoder gem 允许在测试时存根:https ://github.com/alexreisner/geocoder#testing

Testing
When writing tests for an app that uses Geocoder it may be useful to avoid network calls and have Geocoder return consistent, configurable results. To do this, configure the :test lookup and/or :ip_lookup

Geocoder.configure(lookup: :test, ip_lookup: :test)
Add stubs to define the results that will be returned:

Geocoder::Lookup::Test.add_stub(
  "New York, NY", [
    {
      'coordinates'  => [40.7143528, -74.0059731],
      'address'      => 'New York, NY, USA',
      'state'        => 'New York',
      'state_code'   => 'NY',
      'country'      => 'United States',
      'country_code' => 'US'
    }
  ]
)

这在调用服务而不指定服务时有效:

results = Geocoder.search(self.address)

但是当我直接在调用中指定服务时,不会发生存根。有没有办法存根这种类型的调用?

results = Geocoder.search(self.address, lookup: :google)

我是 ruby​​ 和 rails 的新手,如果有任何帮助,我将不胜感激。

标签: ruby-on-railsrubygeocoder

解决方案


示例代码中有一个小错误。应该是Geocoder.search(self.address, lookup: :google)。只是提到它,因为它最初让我失望。

通读源代码后,很明显存根和指定服务不能一起工作。

name = options[:lookup] || Configuration.lookup || Geocoder::Lookup.street_services.first

当它确定要使用的服务时,这是来自 Query 类的代码。您可以看到它首先检查通过的查找服务选项,然后检查配置(已设置为测试),然后使用默认服务,该服务只是列表中的第一个。

最简单的解决方案是使用 VCR(和 Webmock)gem。它将实时网络请求的结果记录到文件中,并以文件内容响应测试的所有未来请求。停止实时网络请求,让您不必创建模拟数据。

https://github.com/vcr/vcr


推荐阅读