简体   繁体   English

如何测试(使用RSpec)在Rails中发送HTTP请求(作为单元测试的一部分)?

[英]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. 我在Gateway类中获得了此代码,该类向公司内部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. connection是法拉第请求对象,而expecting是一种使该方法知道其期望有效响应的状态的方法。 Both are defined in the BaseGateway from which the XGateway inherits. 两者都在XGateway继承的BaseGateway中定义。

Now what do I need to test here (in the scope of a Unit Test?) 现在我需要在这里进行什么测试(在单元测试的范围内?)

As far as I understand, for every method: 据我了解,每种方法:

  • Test that an HTTP request is send with the correct params 测试使用正确的参数发送HTTP请求
  • Test for the right behaviour when expecting is fulfilled (response has status code 204) 满足期望时测试正确的行为(响应的状态码为204)
  • Test for the right behaviour when expecting is not fulfilled (response has status code different than 204) 在未达到期望时测试正确的行为(响应的状态码不同于204)

But, how can I test that an http request has been send? 但是,如何测试HTTP请求已发送?

Normally I use VCR for testing requests and responses. 通常,我使用VCR来测试请求和响应。 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. VCR的主要目的是加快测试套件的速度,使其对第三方系统的更改更加健壮。

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. 你的情况,你可以设置的单元测试,你传递给PARAMS的activatedeactivate对您从输入期望的响应方法和测试。

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. 您可以(尽管我不建议这样做)解析vcr盒式磁带,以查找请求URL所在的部分,并将其与您的期望相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM