Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily setting system time with Ruby for unit testing

I've created a custom validation on a Apt model that verifies that an appointment can't be booked for the next day if the form submission is done after 3 PM and I'm trying to determine the best way to run the unit tests to verify that my custom validation is working correctly.

Currently, my test contains an if statement to to check if the test is run before or after 3 PM and uses a different test based on the current system time. However, I'd like to be able to test both cases no matter what the system time is.

test "booking appointment for tomorrow before/after three pm" do
  a = appointments(:aptone)

  # Set appointment date to tomorrow
  a.apt_date = DateTime.current + 1.day

  if (Time.current.hour >= 12)
    assert(a.invalid?, 'Appointment CANNOT be booked after 3 PM')
  elsif
    assert(a.valid?, 'Appointment CAN be booked before 3 PM')
  end
end

I'm wondering if there is a way to temporarily set the system time while running the test so that I can test both assertions regardless of when the tests are ran.

like image 214
dspencer Avatar asked Dec 16 '22 21:12

dspencer


1 Answers

I can strongly recommend the timecop gem which was written for exactly the requirements you mentioned. Have a look at the documentation on the github page, specifically the freeze method (or travel, but it is better to test against a frozen system time in your example).

like image 75
emrass Avatar answered Jan 14 '23 13:01

emrass