Skip to content

Commit 207c85f

Browse files
rafaelbeauby
authored andcommitted
Add tests for meta on resource objects.
1 parent 0bd5c65 commit 207c85f

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
require 'test_helper'
2+
3+
module ActiveModel
4+
class Serializer
5+
module Adapter
6+
class JsonApi
7+
class ResourceMetaTest < Minitest::Test
8+
class MetaHashPostSerializer < ActiveModel::Serializer
9+
attributes :id
10+
meta stuff: 'value'
11+
end
12+
13+
class MetaBlockPostSerializer < ActiveModel::Serializer
14+
attributes :id
15+
meta do
16+
{ comments_count: object.comments.count }
17+
end
18+
end
19+
20+
def setup
21+
@post = Post.new(id: 1337, comments: [], author: nil)
22+
end
23+
24+
def test_meta_hash_object_resource
25+
hash = ActiveModel::SerializableResource.new(
26+
@post,
27+
serializer: MetaHashPostSerializer,
28+
adapter: :json_api
29+
).serializable_hash
30+
expected = {
31+
stuff: 'value'
32+
}
33+
assert_equal(expected, hash[:data][:meta])
34+
end
35+
36+
def test_meta_block_object_resource
37+
hash = ActiveModel::SerializableResource.new(
38+
@post,
39+
serializer: MetaBlockPostSerializer,
40+
adapter: :json_api
41+
).serializable_hash
42+
expected = {
43+
comments_count: @post.comments.count
44+
}
45+
assert_equal(expected, hash[:data][:meta])
46+
end
47+
48+
def test_meta_object_resource_in_array
49+
hash = ActiveModel::SerializableResource.new(
50+
[@post, @post],
51+
each_serializer: MetaBlockPostSerializer,
52+
adapter: :json_api
53+
).serializable_hash
54+
expected = {
55+
comments_count: @post.comments.count
56+
}
57+
assert_equal([expected, expected], hash[:data].map { |obj| obj[:meta] })
58+
end
59+
end
60+
end
61+
end
62+
end
63+
end

test/serializers/meta_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
module ActiveModel
44
class Serializer
55
class MetaTest < ActiveSupport::TestCase
6+
MetaBlogSerializer = Class.new(ActiveModel::Serializer)
7+
68
def setup
79
@blog = Blog.new(id: 1,
810
name: 'AMS Hints',
@@ -125,6 +127,20 @@ def test_meta_is_present_on_arrays_with_root
125127
}
126128
assert_equal(expected, actual)
127129
end
130+
131+
def test_meta_is_set_with_direct_attributes
132+
MetaBlogSerializer.meta stuff: 'value'
133+
blog_meta_serializer = MetaBlogSerializer.new(@blog)
134+
assert_equal(blog_meta_serializer.meta, stuff: 'value')
135+
end
136+
137+
def test_meta_is_set_with_block
138+
MetaBlogSerializer.meta do
139+
{ articles_count: object.articles.count }
140+
end
141+
blog_meta_serializer = MetaBlogSerializer.new(@blog)
142+
assert_equal(blog_meta_serializer.meta, articles_count: @blog.articles.count)
143+
end
128144
end
129145
end
130146
end

0 commit comments

Comments
 (0)