|
| 1 | +require 'test_helper' |
| 2 | +require 'grape' |
| 3 | +require 'grape/active_model_serializers' |
| 4 | + |
| 5 | +class ActiveModelSerializers::GrapeTest < Minitest::Test |
| 6 | + include Rack::Test::Methods |
| 7 | + |
| 8 | + class GrapeTest < Grape::API |
| 9 | + format :json |
| 10 | + include Grape::ActiveModelSerializers |
| 11 | + |
| 12 | + resources :grape do |
| 13 | + get '/render' do |
| 14 | + render ARModels::Post.new(title: 'Dummy Title', body: 'Lorem Ipsum') |
| 15 | + end |
| 16 | + |
| 17 | + get '/render_with_json_api' do |
| 18 | + post = ARModels::Post.new(title: 'Dummy Title', body: 'Lorem Ipsum') |
| 19 | + render post, meta: { page: 1, total_pages: 2 }, adapter: :json_api |
| 20 | + end |
| 21 | + |
| 22 | + get '/render_array_with_json_api' do |
| 23 | + post = ARModels::Post.create(title: 'Dummy Title', body: 'Lorem Ipsum') |
| 24 | + post.dup.save |
| 25 | + render ARModels::Post.all, adapter: :json_api |
| 26 | + end |
| 27 | + end |
| 28 | + end |
| 29 | + |
| 30 | + def app |
| 31 | + GrapeTest.new |
| 32 | + end |
| 33 | + |
| 34 | + def test_formatter_returns_json |
| 35 | + get '/grape/render' |
| 36 | + |
| 37 | + post = ARModels::Post.new(title: 'Dummy Title', body: 'Lorem Ipsum') |
| 38 | + serializable_resource = serializable(post) |
| 39 | + |
| 40 | + assert last_response.ok? |
| 41 | + assert_equal serializable_resource.to_json, last_response.body |
| 42 | + end |
| 43 | + |
| 44 | + def test_render_helper_passes_through_options_correctly |
| 45 | + get '/grape/render_with_json_api' |
| 46 | + |
| 47 | + post = ARModels::Post.new(title: 'Dummy Title', body: 'Lorem Ipsum') |
| 48 | + serializable_resource = serializable(post, serializer: ARModels::PostSerializer, adapter: :json_api, meta: { page: 1, total_pages: 2 }) |
| 49 | + |
| 50 | + assert last_response.ok? |
| 51 | + assert_equal serializable_resource.to_json, last_response.body |
| 52 | + end |
| 53 | + |
| 54 | + def test_formatter_handles_arrays |
| 55 | + get '/grape/render_array_with_json_api' |
| 56 | + |
| 57 | + expected = { |
| 58 | + 'data' => [ |
| 59 | + { |
| 60 | + id: '1', |
| 61 | + type: 'ar_models_posts', |
| 62 | + attributes: { |
| 63 | + title: 'Dummy Title', |
| 64 | + body: 'Lorem Ipsum' |
| 65 | + }, |
| 66 | + relationships: { |
| 67 | + comments: { data: [] }, |
| 68 | + author: { data: nil } |
| 69 | + } |
| 70 | + }, |
| 71 | + { |
| 72 | + id: '2', |
| 73 | + type: 'ar_models_posts', |
| 74 | + attributes: { |
| 75 | + title: 'Dummy Title', |
| 76 | + body: 'Lorem Ipsum' |
| 77 | + }, |
| 78 | + relationships: { |
| 79 | + comments: { data: [] }, |
| 80 | + author: { data: nil } |
| 81 | + } |
| 82 | + } |
| 83 | + ] |
| 84 | + } |
| 85 | + |
| 86 | + assert last_response.ok? |
| 87 | + assert_equal expected.to_json, last_response.body |
| 88 | + end |
| 89 | +end |
0 commit comments