【问题标题】:validate_presence_of does not produce 'can't be blank' errorvalidate_presence_of 不会产生“不能为空白”错误
【发布时间】:2014-11-10 02:52:25
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      发生这种情况是因为您正在分配国家/地区代码 before_validation,RSPEC 将使用 country code 初始设置为 nil 的模型进行测试,但实际上在验证之前分配了它,因此验证既不可访问且冗余.此验证产生错误的唯一方法是您的地理编码返回nil。如果您删除 before_validation 方法,测试也将通过。

      【讨论】:

      • 这意味着我必须使用before_save,这是我最初的选择。但这导致我的其他测试失败。我创建了一个模型,其中country_code 为空白。 autofill_country_code 方法未运行 before_save
      • 或者你不需要验证这个字段,因为你已经分配了它。你能告诉我另一个测试吗?
      • 为了提供更多上下文,我希望只有在用户未填写country_code 时才运行这段代码。由于是单独的问题,所以我在这里打开了后续问题:stackoverflow.com/questions/26836780/model-running-before-spec
      猜你喜欢
      • 2020-04-20
      • 2012-01-03
      • 2014-08-23
      • 2015-07-23
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多