validate_presence_of不会产生'不能为空'错误

时间:2014-11-10 02:52:26

标签: ruby-on-rails ruby ruby-on-rails-3 rspec

使用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

如果我删除此验证,则测试通过。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

鉴于您所描述的功能,您的代码是正确的,但您的测试是错误的。国家/地区代码 永远不会为零,因此“validate_presence_of”将始终失败。您应该编写测试以确保在验证之前分配country_code。

答案 1 :(得分:0)

这种情况正在发生,因为您要分配国家代码before_validation,RSPEC将测试模型,country code最初设置为nil但实际上在验证之前已分配,因此验证是既不可达也不冗余。如果您的地理编码返回nil,则此验证产生错误的唯一方法。如果您删除before_validation方法,测试也将通过。