require 'rails_helper' RSpec.describe Api::PostsController, type: :controller do describe "index" do describe 'unauthorized' do it 'redirects to login page' do get :index response.redirect_url.should end_with('/users/sign_in') end end describe 'authorized' do before { sign_in create :user } it "no default include, default pagination" do post1 = create :post, title: 'post-1', body: 'post-body-1' comment = create :comment, post: post1 post2 = create :post, title: 'post-2', body: 'post-body-2' get :index assert_json( data: [ { id: post1.id.to_s, type: "post", attributes: {"title"=>"post-1", "body"=>"post-body-1"}, relationships: { comments: {data: [{id: comment.id.to_s , type: "comment" }]} } }, { id: post2.id.to_s, type: "post", attributes: {"title"=>"post-2", "body"=>"post-body-2"}, relationships: { comments: {data: []} } }, ], meta: {"total-pages"=>1, "total-count"=>2} ) end it "does not paginate when index_pagination? is false" do expect( subject ).to receive(:index_pagination?).and_return false post1 = create :post, title: 'post-1', body: 'post-body-1' comment = create :comment, post: post1 post2 = create :post, title: 'post-2', body: 'post-body-2' get :index assert_json( data: [ { id: post1.id.to_s, type: "post", attributes: {"title"=>"post-1", "body"=>"post-body-1"}, relationships: { comments: {data: [{id: comment.id.to_s , type: "comment" }]} } }, { id: post2.id.to_s, type: "post", attributes: {"title"=>"post-2", "body"=>"post-body-2"}, relationships: { comments: {data: []} } }, ] ) end it "includes associations if configured" do expect( subject ).to receive(:index_serialize_options).and_return(include: 'comments') post1 = create :post, title: 'post-1', body: 'post-body-1' comment = create :comment, post: post1, body: 'post-1-comment-1' post2 = create :post, title: 'post-2', body: 'post-body-2' get :index assert_json( data: [ { id: post1.id.to_s, type: "post", attributes: {"title"=>"post-1", "body"=>"post-body-1"}, relationships: { comments: {data: [{id: comment.id.to_s , type: "comment" }]} } }, { id: post2.id.to_s, type: "post", attributes: {"title"=>"post-2", "body"=>"post-body-2"}, relationships: { comments: {data: []} } }, ], included: [ { id: comment.id.to_s, type: "comment", attributes: {body: "post-1-comment-1"}, relationships: { post: {data: {id: post1.id.to_s, type: "post"}} } } ], meta: {"total-pages"=>1, "total-count"=>2} ) end end end end