错误:无法将nil强制转换为Fixnum [英] ERROR: nil can't be coerced into Fixnum
问题描述
首先,这个问题与我之前的问题有点相似,但我觉得有足够的不同来启动新线程.当我尝试在模型上测试验证时,就会出现问题.我有一个用户模型,该模型必须要求字段:default_price.我的测试如下:
First of all, this question is slightly similar to my previous question, but I felt is different enough for me to start a new thread. The problem arises in when I try to test a validation on my model. I have a User model that must require the field :default_price. My test is as follows:
it "should require default packs" do
User.new(FactoryGirl.build(:user, :default_packs => " ")).should_not be_valid
end
但是,当我运行测试时,出现以下错误:
However, when I run the test, I get the following error:
Failure/Error: should_not be_valid
TypeError:
nil can't be coerced into Fixnum
# ./app/models/user.rb:62:in `*'
# ./app/models/user.rb:62:in `daily_saving_potential_cents'
# ./spec/models/user_spec.rb:155:in `block (2 levels) in <top (required)>'
daily_saving_potential_cents定义如下:
The daily_saving_potential_cents is defined as follows:
def daily_saving_potential_cents
return default_price_cents * default_packs
end
default_price_cents
只是default_price
的简化版本,而default_packs是我的模型中的另一个字段.问题源于以下事实:当default_price_cents为空白时,这两个值不能相乘,但是如何在测试中解决此问题?由于进行了验证,因此default_price_cents永远不能为空,但这是我是否要对其进行测试.
default_price_cents
is just a monteized version of default_price
, and default_packs is another field in my model. The problem stems from the fact that these two can't be multiplied together when default_price_cents is blank, but how do I fix this in my tests? Because of my validation, the default_price_cents should never be blank, but it is if I'm testing against it.
推荐答案
我通过使用以下方法简单地确保对新模型定义的验证来解决此问题:
I solved this by simply ensuring the validations on the new model definitions as well, using:
def daily_saving_potential_cents
unless default_price_cents.nil? && default_packs.nil?
return default_price_cents * default_packs
end
end
这篇关于错误:无法将nil强制转换为Fixnum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!