我刚刚发现了Geocoder gem,我的问题与如何通过Rspec测试它的使用有关。 正如我在这里看到的How to test geocoder gem
我创建了一个google_data.json来模拟googlemaps响应,以便每次都不会点击他们的API并且不会消耗我的每日请求数量(而且这样测试真的更快)。当我想测试像这样的函数时,我的问题出现了
def self.find_by_radius_from_location(location, radius=10)
coords = Geocoder.coordinates(location)
Garage.near(coords, radius, units: :km)
end
这是我的测试(如果我连接到gmaps api就可以使用)
describe 'find_by_radius_from_location' do
let!(:garage_inside_radius) { FactoryGirl.create(:turin_garage) }
let!(:garage_outside_radius) { FactoryGirl.create(:rome_garage) }
context 'given a city' do
it 'should return one garage' do
garages = Garage.find_by_radius_from_location('Torino', 10)
garages.first.should eq(garage_inside_radius)
raise garages.inspect
ids = garages.collect { |g| g[:id] }
ids.count.should be(1)
end
end
end
车库坐标是正确的(如果我连接到gmaps,测试通过)我的json有什么问题,因为我收到2个车库而不是1个车库。 这是
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "Via Monginevro 162, Torino, Italy",
"address_components": [ {
"long_name": "Via Monginevro 162",
"short_name": "Via Monginevro 162",
"types": [ "route" ]
}, {
"long_name": "Torino",
"short_name": "Torino",
"types": [ "city", "political" ]
}, {
"long_name": "Italy",
"short_name": "IT",
"types": [ "country", "political" ]
} ],
"geometry": {
"location": {
"lat": 45.0647,
"lng": 7.63015
}
}
}, {
"types": [ "street_address" ],
"formatted_address": "Via G. Ferraris 2/4, Roma, Italy",
"address_components": [ {
"long_name": "Via G. Ferraris 2/4",
"short_name": "Via G. Ferraris 2/4",
"types": [ "route" ]
}, {
"long_name": "Roma",
"short_name": "Roma",
"types": [ "city", "political" ]
}, {
"long_name": "Italy",
"short_name": "IT",
"types": [ "country", "political" ]
} ],
"geometry": {
"location": {
"lat": 41.8084,
"lng": 12.3015
}
}
} ]
}
这有什么问题?有没有办法测试我的find_by_radius_from_location
功能?我想我应该只收到一个车库,但我收到2个......为什么?
修改
我找到了一种解决方法,但也许有更好的方法来实现这一目标。
let!(:garage_inside_radius) { FactoryGirl.create(:turin_garage) }
let!(:garage_outside_radius) { FactoryGirl.create(:rome_garage) }
let(:outside_coords) { { latitude: 41.8084, longitude: 12.3015 } }
before(:each) do
garage_outside_radius.update_attributes(outside_coords)
end