简体   繁体   中英

Need help troubleshooting a failing Rspec test - Argument error: Comparison of Date with nil

I'm trying to troubleshoot a test in Rspec. My program code works as expected, but there's a problem in my test code. The relevant rspec contains:

it "is invalid without a date" do
  appointment = FactoryGirl.build(:appointment, date: "")      
  appointment.valid?
  expect(appointment.errors[:date]).to include("can't be blank")
end

Rspec generates the following error:

Failure/Error: appointment.valid?
 ArgumentError:
   comparison of Date with nil failed

It appears the error is caused by my leaving the date field blank to test the scenario (ie, invalid without a date). How do I use Rspec to properly test this scenario if setting date to nil or leaving it blank generates an error? I researched the error message, but didn't find a solution. What's the best approach to deal with the problem?

Your validation method is comparing a Date to nil , hence the error. I can't explain where the empty string you're passing in is getting coerced into nil , but you can't compare a Date to a string either. You need to either rework your validation method to accommodate the full range of potential date values and/or put additional validations in front it (eg presence: true ). Once you do that, your test should be able to run.

It's because of your other validation:

validate :past_dated_appointment

private 

def past_dated_appointment
  if Date.current > self.date
    errors.add(:date, "can't be in the past")
  end
end

You should probably first check that the date is present:

if self.date && Date.current > self.date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM