rubyrspechttparty

Rspec testing Httparty response


I have a definition like this

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

End rspec test:

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

From URL parsing I get hash in which keys are destination_addresses, origin_addresses, distance and duration. How to test by Rspec definition in which the httparty gem is used and, it does not return anything, just writes a parsed field (distance in km) to a variable.


Solution

  • You can stub HTTParty.get method like this working example:

    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
    
    

    You can then export those helper methods into a Helper class inside RSpec suite to use in other places.

    I like to create these helper methods instead of using https://github.com/vcr/vcr because I can control more what I want and use.