Skip to content

Commit f8ca912

Browse files
committed
Add failing test for AMS::Model accessor vs. attributes mutation
1 parent 80af763 commit f8ca912

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

test/active_model_serializers/model_test.rb

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ module ActiveModelSerializers
44
class ModelTest < ActiveSupport::TestCase
55
include ActiveModel::Serializer::Lint::Tests
66

7-
def setup
7+
setup do
88
@resource = ActiveModelSerializers::Model.new
99
end
1010

@@ -18,5 +18,52 @@ def test_initialization_with_string_keys
1818

1919
assert_equal model_instance.read_attribute_for_serialization(:key), value
2020
end
21+
22+
def test_attributes_can_be_read_for_serialization
23+
klass = Class.new(ActiveModelSerializers::Model) do
24+
attributes :one, :two, :three
25+
end
26+
original_attributes = { one: 1, two: 2, three: 3 }
27+
instance = klass.new(original_attributes)
28+
29+
# Initial value
30+
expected_attributes = { id: nil, one: 1, two: 2, three: 3 }.with_indifferent_access
31+
assert_equal expected_attributes, instance.attributes
32+
assert_equal 1, instance.one
33+
assert_equal 1, instance.read_attribute_for_serialization(:one)
34+
35+
# Change via accessor
36+
instance.one = :not_one
37+
38+
expected_attributes = { id: nil, one: :not_one, two: 2, three: 3 }.with_indifferent_access
39+
assert_equal expected_attributes, instance.attributes
40+
assert_equal :not_one, instance.one
41+
assert_equal :not_one, instance.read_attribute_for_serialization(:one)
42+
end
43+
44+
def test_id_attribute_can_be_read_for_serialization
45+
klass = Class.new(ActiveModelSerializers::Model) do
46+
attributes :id, :one, :two, :three
47+
end
48+
self.class.const_set(:SomeTestModel, klass)
49+
original_attributes = { id: :ego, one: 1, two: 2, three: 3 }
50+
instance = klass.new(original_attributes)
51+
52+
# Initial value
53+
expected_attributes = { id: :ego, one: 1, two: 2, three: 3 }.with_indifferent_access
54+
assert_equal expected_attributes, instance.attributes
55+
assert_equal 1, instance.one
56+
assert_equal 1, instance.read_attribute_for_serialization(:one)
57+
58+
# Change via accessor
59+
instance.id = :superego
60+
61+
expected_attributes = { id: :superego, one: 1, two: 2, three: 3 }.with_indifferent_access
62+
assert_equal expected_attributes, instance.attributes
63+
assert_equal :superego, instance.id
64+
assert_equal :superego, instance.read_attribute_for_serialization(:id)
65+
ensure
66+
self.class.send(:remove_const, :SomeTestModel)
67+
end
2168
end
2269
end

0 commit comments

Comments
 (0)