|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'test_helper' |
| 4 | + |
| 5 | +module ActiveModelSerializers |
| 6 | + module Adapter |
| 7 | + class Json |
| 8 | + class FieldsTest < ActiveSupport::TestCase |
| 9 | + class Post < ::Model |
| 10 | + attributes :title, :body |
| 11 | + associations :author, :comments |
| 12 | + end |
| 13 | + class Author < ::Model |
| 14 | + attributes :name, :birthday |
| 15 | + end |
| 16 | + class Comment < ::Model |
| 17 | + attributes :title, :body |
| 18 | + associations :author, :post |
| 19 | + end |
| 20 | + |
| 21 | + class PostSerializer < ActiveModel::Serializer |
| 22 | + type 'post' |
| 23 | + attributes :title, :body |
| 24 | + belongs_to :author |
| 25 | + has_many :comments |
| 26 | + end |
| 27 | + |
| 28 | + class AuthorSerializer < ActiveModel::Serializer |
| 29 | + attributes :name, :birthday |
| 30 | + end |
| 31 | + |
| 32 | + class CommentSerializer < ActiveModel::Serializer |
| 33 | + type 'comment' |
| 34 | + attributes :title, :body |
| 35 | + belongs_to :author |
| 36 | + end |
| 37 | + |
| 38 | + def setup |
| 39 | + @author = Author.new(id: 1, name: 'Lucas', birthday: '10.01.1990') |
| 40 | + @comment1 = Comment.new(id: 7, body: 'cool', author: @author) |
| 41 | + @comment2 = Comment.new(id: 12, body: 'awesome', author: @author) |
| 42 | + @post = Post.new(id: 1337, title: 'Title 1', body: 'Body 1', |
| 43 | + author: @author, comments: [@comment1, @comment2]) |
| 44 | + @comment1.post = @post |
| 45 | + @comment2.post = @post |
| 46 | + end |
| 47 | + |
| 48 | + def test_fields_attributes |
| 49 | + fields = [:title] |
| 50 | + hash = serializable(@post, adapter: :json, fields: fields, include: []).serializable_hash |
| 51 | + expected = { title: 'Title 1' } |
| 52 | + assert_equal(expected, hash[:post]) |
| 53 | + end |
| 54 | + |
| 55 | + def test_fields_included |
| 56 | + fields = [:title, { comments: [:body] }] |
| 57 | + hash = serializable(@post, adapter: :json, include: [:comments], fields: fields).serializable_hash |
| 58 | + expected = [{ body: @comment1.body }, { body: @comment2.body }] |
| 59 | + |
| 60 | + assert_equal(expected, hash[:post][:comments]) |
| 61 | + end |
| 62 | + end |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments