【问题标题】:Rspec testing Httparty responseRspec 测试 Httparty 响应
【发布时间】:2021-08-18 18:18:57
【问题描述】:

我有这样的定义

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 解析中,我得到哈希,其中键是目标地址、原始地址、距离和持续时间。 如何通过使用 httparty gem 的 Rspec 定义进行测试,它不返回任何内容,只是将解析的字段(以 km 为单位的距离)写入变量。

【问题讨论】:

    标签: ruby rspec httparty


    【解决方案1】:

    您可以像这个工作示例一样存根 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 套件中的 Helper 类中,以便在其他地方使用。

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

    【讨论】:

    • 感谢您的帮助。用于存根请求的 Webmock 怎么样?你能帮我解决这个问题吗?
    • 我从未使用过 Webmock,但似乎也是一个非常好的解决方案。在引擎盖下它会做类似这里的例子的事情,但我认为以更灵活的方式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多