Flip
Flip

Reputation: 6761

How can I test (with RSpec) that an HTTP request is send in Rails (as part of an unit test)?

I've got this code in a Gateway class, which makes requests to an company-internal API. How do I unit test it?

class XGateway < BaseGateway
  self.target_url = ENV["X_URL"]

  def activate(serial_number:, comment: nil)
    expecting 204 do
      connection.put do |req|
        req.url "/api/v1/hw/#{serial_number}/activate"
        req.params = { comment: comment }
      end
    end
  end

  def deactivate(serial_number:, comment: nil)
    expecting 204 do
      connection.put do |req|
        req.url "/api/v1/hw/#{serial_number}/deactivate"
        req.params = { comment: comment }
      end
    end
  end
end

The connection is a Faraday request object and expecting is a method to let the method know which status it expects for valid responses. Both are defined in the BaseGateway from which the XGateway inherits.

Now what do I need to test here (in the scope of a Unit Test?)

As far as I understand, for every method:

But, how can I test that an http request has been send?

Upvotes: 0

Views: 2483

Answers (1)

basiszwo
basiszwo

Reputation: 620

Normally I use VCR for testing requests and responses. With this you can record the request and response made in your code. The main purpose of VCR is to speed up your test suite and make it more robust against changes in third party systems.

In your case you could setup unit tests where you pass params to the activate and deactivate methods and test against the responses you are expecting from the inputs.

You could (although I cannot recommend this) parse the vcr cassette for the part where the request url is located and match it against your expectation.

Upvotes: 1

Related Questions