使用validates_presence_of和validates_numericality_of时验证失败

时间:2011-11-09 13:47:10

标签: ruby-on-rails ruby validation rspec

我需要验证模型中的数据,然后使用rspec测试此模型:

以下是模型中的验证:

validates_presence_of :sales_price
validates_presence_of :retail_price

validates_numericality_of :sales_price, :greater_than => 0
validates_numericality_of :retail_price,:greater_than => 0
validates_numericality_of :sales_price, :less_than => :retail_price,
                                          :message => "must be less than retail price."

当我试图测试这样的模型时

it { should validate_presence_of :sales_price }
it { should validate_presence_of :retail_price }
it { should validate_numericality_of :sales_price }
it { should validate_numericality_of :retail_price }

我收到此错误

Failure/Error: it { should validate_presence_of :retail_price }
 ArgumentError:
   comparison of Float with nil failed
 # ./spec/models/offer_option_spec.rb:19:in `block (2 levels) in <top (required)>'

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

@sled是正确的,nil检查内置于validates_numericality_of中,默认情况下已启用,因此不必同时满足这两个要求。

另外需要注意的是,销售价格确实是两次验证数值,这可能会导致问题。我会把它改成

validates_numericality_of :sales_price, :greater_than => 0, :less_than => :retail_price, :message => "must be less than retail price."

答案 1 :(得分:3)

感谢您的回答。

我终于明白了。

validates_numericality_of :sales_price, :greater_than => 0,
                        :allow_blank => true
validates_numericality_of :retail_price, :greater_than => 0,
                        :allow_blank => true
validates_numericality_of :sales_price, :less_than => :retail_price,
                        :if => Proc.new { |o| !o.retail_price.nil? } ,
                        :message => "can't be greater than retail price."

现在我又遇到了另一个问题。我使用rails.validation.js帮助我执行客户端验证。如果你在数字验证器中使用这样的东西,一切都很好:

:greater_than => 0

validation.js创建一个函数,检查字段中的值是否大于0.函数创建如下:

new Function("return " + element.val() + CHECKS[check] + options[check])()))

元素是我的输入字段, CHECKS包含不同的散列:less_than:&lt;,greater_than:&gt;等 options [check]包含一些传递给验证器的值(:greater_than =&gt; 0,在这种情况下为0,options [check]为less_than:&#39; 0&#39;)。但是当我使用其他东西而不是值时,我会收到错误:

Uncaught ReferenceError: retail_price is not defined 

我试过这样的事情

validates_numericality_of :sales_price, :less_than => Proc.new{ self.retail_price },
                        :if => Proc.new { |o| !o.retail_price.nil? } ,
                        :message => "can't be greater than retail price."

但是在执行验证时该对象不存在,因此self只指向该类,而retail_price不存在。

你会建议什么来解决这个问题?