2016-09-25 6 views
0

私はrillingをBillingモデルで実行するとき、nil:NilClassのために未定義のメソッド`>'を使い続けます。以下は、私はRSpecのRails Rspec - nilのモデル属性未定義メソッド `> ':NilClass

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 

、それらのすべてがこれを示すを実行したときに、私はこのエラーを取得するモデル

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 

ための私のコードですエラー

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の両方の存在を検証しており、それでも私にエラーを与えています。私はこれらの変更を含めるように質問を更新します – Josiah

+0

カスタムバリデータも変更しましたか?私は私の答えの中で「条件」を変えます。日付が 'nil'でないことを確認する必要があるので、例えば:' start_date && start_date> Time.current.to_date' – spickermann

+0

@Josiahが正しいとすれば、これで問題は解決します。プレゼンスバリデーターはカスタムバリデータの前に実行されることは保証されていないので、 'start_date'などがnilでない場合も考慮する必要があります。 –

関連する問題