2016-09-25 39 views
0

当我在结算模型上运行我的rspec时,我总是收到nil:NilClass的错误未定义方法`>'。下面是我对模型Rails Rspec - model属性undefined方法`>'为零:NilClass

class Billing < ActiveRecord::Base 
    validate :start_date, :end_date, presence: true 
    validate :is_valid_date? 

    def is_valid_date? 
    errors.add(:start_date, 'must be in the past') if start_date > Time.current.to_date 
    errors.add(:end_date, 'must be in the past') if end_date > Time.current.to_date 
    errors.add(:end_date, 'must be more than or equal to start date') if start_date > end_date 
    end 
end 

代码,这是我的RSpec的

require 'rails_helper' 
RSpec.describe FamilyBilling, type: :model do 
    it { should validate_presence_of(:start_date) } 
    it { should validate_presence_of(:end_date) } 
    it { should validate_presence_of(:amount) } 
    it { should validate_presence_of(:hours) } 
    it { should validate_presence_of(:rate) } 
    it { should validate_presence_of(:processing_fee) }  
    it { should_not validate_presence_of(:tip) } 
end 

我得到当我运行rspec的

Failed examples: 
rspec ./spec/models/billing_spec.rb:8 # Billing should require start_date to be set 
rspec ./spec/models/billing_spec.rb:9 # Billing should require end_date to be set 
rspec ./spec/models/billing_spec.rb:10 # Billing should require amount to be set 
rspec ./spec/models/billing_spec.rb:11 # Billing should require hours to be set 
rspec ./spec/models/billing_spec.rb:12 # Billing should require rate to be set 
rspec ./spec/models/billing_spec.rb:13 # Billing should require processing_fee to be set 
rspec ./spec/models/billing_spec.rb:14 # Billing should not require tip to be set 

,他们都表示这此错误代码错误

Failure/Error: errors.add(:start_date, 'must be in the past') if start_date > Time.current.to_date 

NoMethodError: 
    undefined method `>' for nil:NilClass 

我做了什么做错了?

+1

哪条线?包含整个错误,所以我们不必猜测 –

回答

3

您的自定义验证程序预计start_dateend_date必须存在。如果他们不存在该错误抛出 - 例如在这里:start_date > Time.current.to_date

因此,你应该明确地验证他们的存在,并检查它们是否出现在您的自定义验证:

class Billing < ActiveRecord::Base 
    validates :start_date, :end_date, presence: true 
    validate :dates_valid? 

    def dates_valid? 
    errors.add(:start_date, 'must be in the past') if start_date && start_date > Time.current.to_date 
    errors.add(:end_date, 'must be in the past') if end_date && end_date > Time.current.to_date 
    errors.add(:end_date, 'must be more than or equal to start date') if start_date && end_date && start_date > end_date 
    end 
end 
+0

我在start_date和end_date上都有validate存在,它仍然给我错误。我将更新我的问题以包含这些更改 – Josiah

+0

您是否也更改了自定义验证器?我在我的答案中更改了“if”条件。因为你需要检查日期不是'nil',例如像这样:'if start_date && start_date> Time.current.to_date' – spickermann

+0

@Josiah是对的,这应该解决这个问题。验证器不能保证在你的自定义验证器之前运行,所以你仍然需要考虑'start_date'等可能为零的情况。 –

相关问题