问题
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)>'
The daily_saving_potential_cents is defined as follows:
def daily_saving_potential_cents
return default_price_cents * default_packs
end
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.
回答1:
From your code you are passing user object parameter to User.new. I think you supposed to use
User.new(FactoryGirl.attributes_for(:user, :default_packs => " "))
Please try it.
回答2:
The reason for this issue is any arithmetic operation of integer with nil, For Ex.
1 + nil
1 * nil
etc.
You can handle it by only checking whether second arg is nil or not.
回答3:
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
来源:https://stackoverflow.com/questions/24061776/error-nil-cant-be-coerced-into-fixnum