Skip to content

Commit 7af1986

Browse files
committed
Add tests for conditional attributes/associations.
1 parent 7fbf7e5 commit 7af1986

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

test/serializers/associations_test.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,29 @@ def test_associations_namespaced_resources
238238
end
239239
end
240240
end
241+
242+
def test_conditional_associations
243+
serializer = Class.new(ActiveModel::Serializer) do
244+
belongs_to :if_assoc_included, if: :true
245+
belongs_to :if_assoc_excluded, if: :false
246+
belongs_to :unless_assoc_included, unless: :false
247+
belongs_to :unless_assoc_excluded, unless: :true
248+
249+
def true
250+
true
251+
end
252+
253+
def false
254+
false
255+
end
256+
end
257+
258+
model = ::Model.new
259+
hash = serializable(model, serializer: serializer).serializable_hash
260+
expected = { if_assoc_included: nil, unless_assoc_included: nil }
261+
262+
assert_equal(expected, hash)
263+
end
241264
end
242265
end
243266
end

test/serializers/attribute_test.rb

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ module ActiveModel
44
class Serializer
55
class AttributeTest < ActiveSupport::TestCase
66
def setup
7-
@blog = Blog.new({ id: 1, name: 'AMS Hints', type: 'stuff' })
7+
@blog = Blog.new(id: 1, name: 'AMS Hints', type: 'stuff')
88
@blog_serializer = AlternateBlogSerializer.new(@blog)
99
end
1010

@@ -95,6 +95,29 @@ def test_virtual_attribute_block
9595

9696
assert_equal(expected, hash)
9797
end
98+
99+
def test_conditional_attributes
100+
serializer = Class.new(ActiveModel::Serializer) do
101+
attribute :if_attribute_included, if: :true
102+
attribute :if_attribute_excluded, if: :false
103+
attribute :unless_attribute_included, unless: :false
104+
attribute :unless_attribute_excluded, unless: :true
105+
106+
def true
107+
true
108+
end
109+
110+
def false
111+
false
112+
end
113+
end
114+
115+
model = ::Model.new
116+
hash = serializable(model, serializer: serializer).serializable_hash
117+
expected = { if_attribute_included: nil, unless_attribute_included: nil }
118+
119+
assert_equal(expected, hash)
120+
end
98121
end
99122
end
100123
end

0 commit comments

Comments
 (0)