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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With