2016-09-25 62 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'等可能爲零的情況。 –

相關問題