使用rspec进行Rails Geocoder测试

问题描述 投票:6回答:1

我正在尝试设置我的RSpec测试以使用存根而不是使用网络来进行地理编码。

我补充说:

before(:each) do
Geocoder.configure(:lookup => :test)
Geocoder::Lookup::Test.add_stub(
    "Los Angeles, CA", [{
                            :latitude    => 34.052363,
                            :longitude    => -118.256551,
                            :address      => 'Los Angeles, CA, USA',
                            :state        => 'California',
                            :state_code   => 'CA',
                            :country      => 'United States',
                            :country_code => 'US'
                        }],

)

结束

我正在使用FactoryGirl来创建测试数据,如下所示:

FactoryGirl.define do
    factory :market do
    city 'Los Angeles'
    state 'CA'
    radius 20.0
  end
end

正确地对纬度/经度进行地理编码并以纬度/经度存储。但是,当我尝试:

Market.near(params[:search])

它返回nil ..但是,如果我只是使用lookup =>:google它就像我打算一样。有没有人以前有这个工作,特别是地理编码器的近距离方法?

ruby-on-rails rspec rails-geocoder
1个回答
5
投票

我最终在一个新项目上重新回到了这个问题,然后想出来了。

地理编码器上的文档实际上声明哈希必须有字符串键而不是符号。 geocoder docs - see notes

before(:each) do
    Geocoder.configure(:lookup => :test)
    Geocoder::Lookup::Test.add_stub(
        "Los Angeles, CA", [{
                                "latitude"    => 34.052363,
                                "longitude"    => -118.256551,
                                "address"      => 'Los Angeles, CA, USA',
                                "state"        => 'California',
                                "state_code"   => 'CA',
                                "country"      => 'United States',
                                "country_code" => 'US'
                            }],

    )
end

而不是我在原帖中怎么做的:

即yaazkssvpoi

我最终做了一些更有活力的事情:

:latitude => 34.052363

在我的工厂:

# frozen_string_literal: true

module GeocoderStub
  def self.stub_with(facility)
    Geocoder.configure(lookup: :test)

    results = [
      {
          'latitude' => Faker::Address.latitude.first(9),
          'longitude' => Faker::Address.longitude.first(9)
      }
    ]

    queries = [facility.full_address, facility.zip]
    queries.each { |q| Geocoder::Lookup::Test.add_stub(q, results) }
  end
end

这为每个Facility工厂添加了一个地理编码器存根,该工厂是为完整地址(设施中定义的方法)和zip构建的。

© www.soinside.com 2019 - 2024. All rights reserved.