我一直得到错误未定义的方法`>'对于nil:当我在Billing模型上运行我的rspec时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
我做错了什么?
答案 0 :(得分:3)
您的自定义验证程序希望start_date
和end_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