本文介绍了Ruby on Rails - 随机失败的 RSpec 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

抱歉我的愚蠢问题.

为了检查邮政编码的验证,我添加了外部 api 以获得响应.

I added the external api to get response in order to check zipcode's validation.

app/validators/zipcode_validator.rb

app/validators/zipcode_validator.rb

class ZipcodeValidator < ActiveModel::Validator
  def validate(record)
    record.errors.add(:zipcode, :blank) if record.zipcode.blank?
    record.errors.add(:zipcode, :not_found) if WmsService.wms_delivery_dates(record.zipcode).nil?
  end
end

它在实际中运行良好,但随机失败并且在我运行 rspec 时花费了更多时间.

It works fine in real but failed randomly and took more time when I run rspec.

这种情况有什么好的解决方案?

What's the good solution for this situation?

推荐答案

您不应在测试中调用外部 API.有几种方法可以避免它:

You should not call external APIs in your tests. There are several methods to avoid it:

  1. VCR gem 在第一次调用时记录 API 响应,然后从磁盘回复它(即快速且可靠).
  2. 模拟 HTTP 调用,例如使用 WebMock.您需要编写指定的模拟请求并在规范中编写响应.它可以帮助您提高测试可读性,也有助于测试边缘情况.
  3. 将您的服务调用包装在您的类中,并将其替换为 RSpec 存根.
  4. 将您的服务调用封装在接受适配器的类中.适配器负责调用外部服务.在测试环境中,通过具有预定响应的测试适配器.
  1. VCR gem records API response in first call then then replies it from disk (that is fast and reliable).
  2. Mocking HTTP calls, e.g. with WebMock. You need to write specify mocked request and write a response in your specs. It may help you improve test readability also it helps in testing edge cases.
  3. Wrap your service call in your class and replace it with an RSpec stub.
  4. Wrap your service call in your class that accepts adapters. An adapter is responsible for calling external service. In test env pass a test adapter with predetermined responses.

这篇关于Ruby on Rails - 随机失败的 RSpec 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:12