问题
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:
- VCR gem records API response in first call then then replies it from disk (that is fast and reliable).
- 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.
- Wrap your service call in your class and replace it with an RSpec stub.
- 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