Rspec 测试 Httparty 响应

Rspec testing Httparty response

我有这样的定义

require 'httparty'
def distance_calculation
    url = "https://api.distancematrix.ai/maps/api/distancematrix/json?origins=# 
    {@departure}&destinations=#{@destination}&key=lugtcyuuvliub;o;o"
    response = HTTParty.get(url)
    distance = response.parsed_response["rows"].first["elements"].first["distance"]. 
    ["text"]

end

结束rspec测试:

describe "#cargo" do
  context "distance" do
    it "returns hash with destination addresses, origin addresses & rows of datas" do
  end
end

从 URL 解析中我得到散列,其中的键是 destination_addresses、origin_addresses、距离和持续时间。 如何通过 Rspec 定义进行测试,其中使用了 httparty gem,它没有 return 任何东西,只是将解析的字段(以公里为单位的距离)写入变量。

您可以存根 HTTParty.get 方法,就像这个工作示例:

require "rails_helper"

class MyClass
  def distance_calculation
    url = "https://api.distancematrix.ai/maps/api/distancematrix/json?origins=foo&destinations=bar&key=lugtcyuuvliub;o;o"
    response = HTTParty.get(url)
    distance = response.parsed_response["rows"].first["elements"].first["distance"]["text"]
  end
end

RSpec.describe MyClass do
  # you can write some helper methods inside your class test
  def wrap_elements_body(elements)
    {
      rows: [{
        elements: elements
      }]
    }
  end

  def build_distance_body_response(distance)
    item = { distance: { text: distance } }
    wrap_elements_body([item])
  end

  def stub_request_with(body)
    body = JSON.parse(body.to_json) # just to convert symbol keys into string
    response = double(parsed_response: body)

    allow(HTTParty).to receive(:get).and_return(response)
  end


  describe "#cargo" do
    context "distance" do
      it "returns hash with destination addresses, origin addresses & rows of datas" do

        # stubbing 
        expected_distance = 100.0
        body_response = build_distance_body_response(expected_distance)
        stub_request_with(body_response)

        # running 
        calculated_distance = described_class.new.distance_calculation

        # expectations
        expect(calculated_distance).to eq(expected_distance)
      end
    end
  end
end

然后您可以将这些辅助方法导出到 RSpec 套件内的辅助 class 中,以便在其他地方使用。

我喜欢创建这些辅助方法而不是使用 https://github.com/vcr/vcr 因为我可以控制更多我想要和使用的东西。