0

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

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

4

1 回答 1

0

Since total_price runs before validation, quantity can be nil at the time the callback is executed. This is in fact what happens behind the scenes when the Shoulda matcher runs, which is why you get an error. It's trying to send the * method to quantity, which is nil.

Use after_validation or before_save instead.

于 2013-06-14T17:18:09.807 回答