使用 validate_presence_of
时,我从 rspec 收到此错误:
Expected errors to include "can't be blank" when country_code is set to nil
这可能是由于我写的这一行而发生的:before_validation :autofill_country_code
它执行以下操作:
def autofill_country_code
unless self.country_code.present?
country = GeoCache.geocode(self.city).country_code
country_code = IsoCountryCodes.find(country).calling
self.country_code = country_code.tr('+', '')
end
end
如果我删除此验证,测试就会通过。我该如何解决这个问题?
最佳答案
鉴于您所描述的功能,您的代码是正确的,但您的测试是错误的。国家/地区代码永远不会为零,因此“validate_presence_of”将始终失败。您应该编写一个测试来确保在验证之前分配country_code。
关于ruby-on-rails - validate_presence_of 不会产生 'can' t be Blank' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26836001/