|
| 1 | +require 'test_helper' |
| 2 | + |
| 3 | +module ActiveModel |
| 4 | + class Serializer |
| 5 | + module Adapter |
| 6 | + class JsonApi |
| 7 | + class TopLevelJsonApiTest < Minitest::Test |
| 8 | + def setup |
| 9 | + @author = Author.new(id: 1, name: 'Steve K.') |
| 10 | + @author.bio = nil |
| 11 | + @author.roles = [] |
| 12 | + @blog = Blog.new(id: 23, name: 'AMS Blog') |
| 13 | + @post = Post.new(id: 42, title: 'New Post', body: 'Body') |
| 14 | + @anonymous_post = Post.new(id: 43, title: 'Hello!!', body: 'Hello, world!!') |
| 15 | + @comment = Comment.new(id: 1, body: 'ZOMG A COMMENT') |
| 16 | + @post.comments = [@comment] |
| 17 | + @post.blog = @blog |
| 18 | + @anonymous_post.comments = [] |
| 19 | + @anonymous_post.blog = nil |
| 20 | + @comment.post = @post |
| 21 | + @comment.author = nil |
| 22 | + @post.author = @author |
| 23 | + @anonymous_post.author = nil |
| 24 | + @blog = Blog.new(id: 1, name: 'My Blog!!') |
| 25 | + @blog.writer = @author |
| 26 | + @blog.articles = [@post, @anonymous_post] |
| 27 | + @author.posts = [] |
| 28 | + end |
| 29 | + |
| 30 | + def test_toplevel_jsonapi_defaults_to_false |
| 31 | + assert_equal config.fetch(:jsonapi_include_toplevel_object), false |
| 32 | + end |
| 33 | + |
| 34 | + def test_disable_toplevel_jsonapi |
| 35 | + with_config(jsonapi_include_toplevel_object: false) do |
| 36 | + hash = serialize(@post) |
| 37 | + assert_nil(hash[:jsonapi]) |
| 38 | + end |
| 39 | + end |
| 40 | + |
| 41 | + def test_enable_toplevel_jsonapi |
| 42 | + with_config(jsonapi_include_toplevel_object: true) do |
| 43 | + hash = serialize(@post) |
| 44 | + refute_nil(hash[:jsonapi]) |
| 45 | + end |
| 46 | + end |
| 47 | + |
| 48 | + def test_default_toplevel_jsonapi_version |
| 49 | + with_config(jsonapi_include_toplevel_object: true) do |
| 50 | + hash = serialize(@post) |
| 51 | + assert_equal('1.0', hash[:jsonapi][:version]) |
| 52 | + end |
| 53 | + end |
| 54 | + |
| 55 | + def test_toplevel_jsonapi_no_meta |
| 56 | + with_config(jsonapi_include_toplevel_object: true) do |
| 57 | + hash = serialize(@post) |
| 58 | + assert_nil(hash[:jsonapi][:meta]) |
| 59 | + end |
| 60 | + end |
| 61 | + |
| 62 | + def test_toplevel_jsonapi_meta |
| 63 | + new_config = { |
| 64 | + jsonapi_include_toplevel_object: true, |
| 65 | + jsonapi_toplevel_meta: { |
| 66 | + 'copyright' => 'Copyright 2015 Example Corp.' |
| 67 | + } |
| 68 | + } |
| 69 | + with_config(new_config) do |
| 70 | + hash = serialize(@post) |
| 71 | + assert_equal(new_config[:jsonapi_toplevel_meta], hash.fetch(:jsonapi).fetch(:meta)) |
| 72 | + end |
| 73 | + end |
| 74 | + |
| 75 | + private |
| 76 | + |
| 77 | + def serialize(resource, options = {}) |
| 78 | + serializable(resource, { adapter: :json_api }.merge!(options)).serializable_hash |
| 79 | + end |
| 80 | + end |
| 81 | + end |
| 82 | + end |
| 83 | + end |
| 84 | +end |
0 commit comments