1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
# frozen_string_literal: true
module ActiveModel
class Serializer
class SerializationTest < ActiveSupport::TestCase
class Blog < ActiveModelSerializers::Model
attributes :id, :name, :authors
end
class Author < ActiveModelSerializers::Model
attributes :id, :name
end
class BlogSerializer < ActiveModel::Serializer
attributes :id
attribute :name, key: :title
has_many :authors
end
class AuthorSerializer < ActiveModel::Serializer
attributes :id, :name
end
setup do
@authors = [Author.new(id: 1, name: 'Blog Author')]
@blog = Blog.new(id: 2, name: 'The Blog', authors: @authors)
@serializer_instance = BlogSerializer.new(@blog)
@serializable = ActiveModelSerializers::SerializableResource.new(@blog, serializer: BlogSerializer, adapter: :attributes)
@expected_hash = { id: 2, title: 'The Blog', authors: [{ id: 1, name: 'Blog Author' }] }
@expected_json = '{"id":2,"title":"The Blog","authors":[{"id":1,"name":"Blog Author"}]}'
end
test '#serializable_hash is the same as generated by the attributes adapter' do
assert_equal @serializable.serializable_hash, @serializer_instance.serializable_hash
assert_equal @expected_hash, @serializer_instance.serializable_hash
end
test '#as_json is the same as generated by the attributes adapter' do
assert_equal @serializable.as_json, @serializer_instance.as_json
assert_equal @expected_hash, @serializer_instance.as_json
end
test '#to_json is the same as generated by the attributes adapter' do
assert_equal @serializable.to_json, @serializer_instance.to_json
assert_equal @expected_json, @serializer_instance.to_json
end
test '#to_h is an alias for #serializable_hash' do
assert_equal @serializable.serializable_hash, @serializer_instance.to_h
assert_equal @expected_hash, @serializer_instance.to_h
end
test '#to_hash is an alias for #serializable_hash' do
assert_equal @serializable.serializable_hash, @serializer_instance.to_hash
assert_equal @expected_hash, @serializer_instance.to_hash
end
end
end
end
|