active_model_serializers/test/action_controller/json_api/fields_test.rb
L. Preston Sego III a319fef239 Add tests for fields option demonstrating usage on both attributes and relationships (#1839)
* add test for fields whitelisting relationships, and use the JSON API Include Directive to do the heavy lifting
2016-08-17 16:12:12 -05:00

58 lines
1.8 KiB
Ruby

require 'test_helper'
module ActionController
module Serialization
class JsonApi
class FieldsTest < ActionController::TestCase
class FieldsTestController < ActionController::Base
class PostSerializer < ActiveModel::Serializer
type 'posts'
attributes :title, :body, :publish_at
belongs_to :author
has_many :comments
end
def setup_post
ActionController::Base.cache_store.clear
@author = Author.new(id: 1, first_name: 'Bob', last_name: 'Jones')
@comment1 = Comment.new(id: 7, body: 'cool', author: @author)
@comment2 = Comment.new(id: 12, body: 'awesome', author: @author)
@post = Post.new(id: 1337, title: 'Title 1', body: 'Body 1',
author: @author, comments: [@comment1, @comment2],
publish_at: '2020-03-16T03:55:25.291Z')
@comment1.post = @post
@comment2.post = @post
end
def render_fields_works_on_relationships
setup_post
render json: @post, serializer: PostSerializer, adapter: :json_api, fields: { posts: [:author] }
end
end
tests FieldsTestController
test 'fields works on relationships' do
get :render_fields_works_on_relationships
response = JSON.parse(@response.body)
expected = {
'data' => {
'id' => '1337',
'type' => 'posts',
'relationships' => {
'author' => {
'data' => {
'id' => '1',
'type' => 'authors'
}
}
}
}
}
assert_equal expected, response
end
end
end
end
end