调用特定服务时如何在 ruby​​ 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 的新手,希望得到任何帮助。

解决方法

示例代码中有一个小错误。应该是 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