Ruby on Rails - Randomly failing RSpec tests

时间秒杀一切 提交于 2019-12-22 12:19:29

问题


Sorry for my stupid question.

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

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

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

What's the good solution for this situation?


回答1:


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

  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.


来源:https://stackoverflow.com/questions/53609740/ruby-on-rails-randomly-failing-rspec-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!