Home > Software engineering >  Testing using time helpers
Testing using time helpers

Time:09-12

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

CodePudding user response:

When you create a new Person the value for created_at is not set yet, hence why it returns a nil. That value is typically set only after you save the Person.

So you could do this:

class PersonTest < ActiveSupport::TestCase
  test 'created at matches current time' do
    freeze_time
    person = Person.create.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.
  • Related