Search code examples
ruby-on-rails

Testing using time helpers


I am using the standard tools included in Rails 6 for testing. It's a very simple test, but it seems the freeze_time is not working, and the error code is quite difficult to discern a cause from.

Here is the test I am executing:

enter image description here

Here is the error after running the test:

enter image description here


Solution

  • When you create a new Person the value for created_at should be set (assuming it has timestamps applied), but since you're getting nil instead it is almost certain your Person creation fails. Likely due to validations errors when it tries to save. You could look at the model's error entries to be sure.

    To get the error to show up for viewing:

    class PersonTest < ActiveSupport::TestCase
      test 'created at matches current time' do
        freeze_time
        assert_equal(Time.current, Person.create!.created_at)
      end
    end
    

    If it is a validation error, you can bypass those:

    class PersonTest < ActiveSupport::TestCase
      test 'created at matches current time' do
        freeze_time
        person = Person.new.save(validate: false)
        assert_equal(Time.current, person.created_at)
      end
    end
    

    There are two things wrong with this though.

    1. You want to avoid saving to the DB if at all possible during tests to keep them performant.
    2. You are actually testing Rails's built-in functionality here. This is a test you should not be performing. There may be a better test to check that the Rails timestamps have been applied to your Person model, but that's not one I've ever written before (and I write tests for everything). There is no way to accidentally eliminate the timestamps in a simple commit (it takes an entire accidental migration), so testing for their existence feels way overkill.