Rspec Ruby on Rails:写入单元测试时Haversine gem返回nil值

时间:2018-12-04 10:30:24

标签: ruby-on-rails ruby rspec haversine

我使用Rspec来测试编写的方法,以确保使用Haversine gem到点之间的距离:

# GET /api/v1/angular/sites/:id/distances
  def stores_distances
    site     = Site.find params[ :id ]
    distances = Store.current.map do |store|
      {
        name: store.name,
        value: Haversine.distance(
                site.address.latitude,
                site.address.longitude,
                store.address.latitude,
                store.address.longitude
              ).round(2)
      }
    end

    render json: {
      distances: distances.to_json
    }
  end

我要测试2种情况:如果该方法返回200状态,则返回一个距离数组。

这是我所做的:

describe " GET #stores_distances" do
    before :each do
      @site_address   = create :address, latitude: 48.85837009999999, longitude: 2.2944813000000295
      @store_address  = create :address, latitude: 48.8633604, longitude: 2.30189710000002
      @site    = create :site, address: @site_address
      @store   = create :store, address: @store_address

      get :stores_distances, params: { id: @site.id }
    end

    it "should return 200" do
      expect( response.status ).to be_ok
    end

    it "should return an array of distances" do
      expect( response.body ).to have_node(distances)
    end
end

我收到此错误:

  

Api :: V1 :: Angular :: SitesController GET #stores_distances应该   回报200        失败/错误:          值:Haversine.distance(                  site.address.latitude,                  site.address.longitude,                  store.address.latitude,                  store.address.longitude                ).round(2)

 TypeError:
   nil can't be coerced into Float

1 个答案:

答案 0 :(得分:1)

似乎其中一家商店有nil纬度或经度。确保从Store.current返回的所有商店都已初始化坐标。