【问题标题】:RSpec Shoulda validates_presence_of nilClassRSpec 应该 validates_presence_of nilClass
【发布时间】:2013-05-08 05:28:16
【问题描述】:

当我使用 Shoulda 的 validates_presence_of 时,它会遇到 before_validation 回调。

before_validation   :set_document, :set_product, :set_price

我正在努力让这个规范通过:

it { should validate_presence_of(:quantity).with_message("Please a quantity.") }

我为订单项的数量、unit_price、tax_rate 和 price 设置了数据库默认值 0。在验证订单项之前,我会根据其他属性计算价格,以防它们发生变化。

对于此计算中涉及的所有属性,我都收到此错误和类似错误:

3) LineItem 
   Failure/Error: it { should validate_presence_of(:quantity).with_message("Please a quantity.") }
   NoMethodError:
     undefined method `*' for nil:NilClass
   # ./app/models/line_item.rb:153:in `total_price'
   # ./app/models/line_item.rb:223:in `set_price'
   # ./spec/models/line_item_spec.rb:32:in `block (2 levels) in <top (required)>'

我的回调 set_price 非常简单:

def set_price
  self.price = total_price
end

total_price 方法也很简单:

def total_price
  quantity * unit_price * (1 + tax_rate/100)
end

如果我完全被难住了,我将不胜感激。我确实看到一些人发布了关于自定义验证方法的帖子。这似乎很基本,我无法弄清楚如何进行。

【问题讨论】:

  • 什么是unit_price?应该是nil
  • unit_price 的数据库默认值为 0,tax_rate、数量和价格也是如此。
  • 因此尝试输出这两个字段的日志值,即nil。和/或尝试使用self.quantityself.unit_price
  • 谢谢。我今天会试试。我想我对与 AR 回调相关的初始化值何时发生感到困惑,并且对 DB 默认值何时发挥作用感到困惑。

标签: ruby-on-rails validation testing rspec shoulda


【解决方案1】:

由于total_price 运行之前 验证,quantity 在执行回调时可以是nil。这实际上是在 Shoulda 匹配器运行时在幕后发生的事情,这就是您收到错误的原因。它正在尝试将* 方法发送到quantity,即nil

请改用after_validationbefore_save

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多