1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Add a missing test case for the persistence behavior of serialize

`serialize` makes the contract that if it is given a class name, it will
never return something other than an instance of that class. This means
that it must cast `nil` to the empty form of that object. As such, we
should then persist empty forms of that object as `nil`. While this is
techincally under the contract of

```
model.attribute = value
assert_equal model.attribute, model.tap(&:save).reload.attribute
```

which we can't actually test universally without property based testing,
it has come up more than once and is worth calling out specifically
since we aren't looking to change it.
This commit is contained in:
Sean Griffin 2015-06-11 16:56:33 -06:00
parent 850d313c3b
commit cd3f5dba1e

View file

@ -274,4 +274,17 @@ class SerializedAttributeTest < ActiveRecord::TestCase
assert_equal({}, topic.content)
end
def test_values_cast_from_nil_are_persisted_as_nil
# This is required to fulfil the following contract, which must be universally
# true in Active Record:
#
# model.attribute = value
# assert_equal model.attribute, model.tap(&:save).reload.attribute
Topic.serialize(:content, Hash)
topic = Topic.create!(content: {})
topic2 = Topic.create!(content: nil)
assert_equal [topic, topic2], Topic.where(content: nil)
end
end