ERROR: nil can't be coerced into Fixnum

我怕爱的太早我们不能终老 提交于 2019-12-12 01:38:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!