jackc / jackc/tod

Rails fixture incorrectly set values for time field

Open
#104 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Ruby
Stars
447
Forks
56
PR merge metrics
No merged PRs in 30d

Description

I have a model with a `time` field like this:
```rb
class MyModel < ApplicationRecord
attribute :my_time, :time_only
end
```

Then in my fixture I set the value like this:
```yaml
one:
my_time: "18:00:00"
```

But when I load the model the field is not set:
```irb
instance.my_time
=> nil
```

Digging a bit deeper I have found that the actual value in the database is this:
```irb
instance.my_time_before_type_cast
=> "2000-01-01 18:00:00"
```

Note that this happens _only_ when using Rails fixtures.

As a quick workaround I added a monkey patch in my initializer:
```rb
# config/initializers/tod.rb
if Rails.env.test?
# Fix for Rails fixtures storing a datetime in time fields.
# The time value is prepended with the date "2000-01-01".
module Tod
class TimeOfDay
class << self
old_try_parse = instance_method(:try_parse)

define_method(:try_parse) do |tod_string|
tod_string = tod_string.to_s
tod_string = tod_string[11..] if tod_string.starts_with? "2000-01-01 "
old_try_parse.bind(self).(tod_string)
end
end
end
end
end
```

I wonder if there's a better way to do that.

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by reproducing the `time_only` attribute with the YAML fixture shown, then inspect the fixture-loading path and the `config/initializers/tod.rb` workaround. Done means a fixture value of `18:00:00` loads into `my_time` correctly without the date-prefixed database value or a test-only monkey patch.

Written by the indexing model from the issue text.

Assessment

Tech stack
rails, ruby
Domain
backend, testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.