I have a model with two custom validation rules. When I remove these rules, RSpec for model validation passes. But adding those validation in model, RSpec can't pass which were previously passing. How can I solve this error and also how can I write RSpec for these custom validations?
My model file leave.rb
class Leave < ApplicationRecord
scope :sorted_asc, lambda { order(id: :asc) }
validates :start_day, :end_day, :reason, :status, presence: true
validate :start_day_cant_be_past, :end_day_cant_be_less_than_start_day
enum category: { 'Sick': 0, 'Leave in Policy': 1, 'Out of Policy': 2 }
def start_day_cant_be_past
if start_day < Date.today
errors.add(:start_day, 'can not be in the past')
end
end
def end_day_cant_be_less_than_start_day
if end_day < start_day
errors.add(:end_day, 'can not be less than start day')
end
end
end
My RSpec file for model leave_spec.rb
require 'rails_helper'
RSpec.describe Leave, type: :model do
it { should define_enum_for(:category).with(['Sick', 'Leave in Policy', 'Out of Policy']) }
it { is_expected.to validate_presence_of(:start_day) }
it { is_expected.to validate_presence_of(:end_day) }
it { is_expected.to validate_presence_of(:reason) }
it { is_expected.to validate_presence_of(:status) }
end
And the error I get is...
Leave should validate that :start_day cannot be empty/falsy
Failure/Error: if start_day < Date.today
NoMethodError:
undefined method `<' for nil:NilClass