Commit a7420b77 authored by Grzegorz Bizon's avatar Grzegorz Bizon

Add specs for standalone pagination for serializers

parent 81eb5c7f
......@@ -12,10 +12,11 @@ class PipelineSerializer < BaseSerializer
end
def represent(resource, opts = {})
if paginated?
raise InvalidResourceError unless resource.respond_to?(:page)
if resource.is_a?(ActiveRecord::Relation)
resource = resource.includes(project: :namespace)
end
if paginated?
super(@paginator.paginate(resource), opts)
else
super(resource, opts)
......
module Gitlab
module Serializer
class Pagination
class InvalidResourceError < StandardError; end
include ::API::Helpers::Pagination
def initialize(request, response)
......@@ -8,6 +9,14 @@ module Gitlab
@response = response
end
def paginate(resource)
if resource.respond_to?(:page)
super(resource)
else
raise InvalidResourceError
end
end
private
# Methods needed by `API::Helpers::Pagination`
......
require 'spec_helper'
describe Gitlab::Serializer::Pagination do
let(:request) { spy('request') }
let(:response) { spy('response') }
before do
allow(request)
.to receive(:query_parameters)
.and_return(params)
end
let(:pagination) { described_class.new(request, response) }
describe '#paginate' do
subject { pagination.paginate(resource) }
let(:resource) { User.all }
let(:params) { { page: 1, per_page: 2 } }
context 'when a multiple resources are present in relation' do
before { create_list(:user, 3) }
it 'correctly paginates the resource' do
expect(subject.count).to be 2
end
it 'appends relevant headers' do
expect(response).to receive(:[]=).with('X-Total', '3')
expect(response).to receive(:[]=).with('X-Total-Pages', '2')
expect(response).to receive(:[]=).with('X-Per-Page', '2')
subject
end
end
context 'when an invalid resource is about to be paginated' do
let(:resource) { create(:user) }
it 'raises error' do
expect { subject }.to raise_error(
described_class::InvalidResourceError)
end
end
end
end
......@@ -58,8 +58,8 @@ describe PipelineSerializer do
let(:pagination) { { page: 1, per_page: 1 } }
it 'raises error' do
expect { subject }
.to raise_error(PipelineSerializer::InvalidResourceError)
expect { subject }.to raise_error(
Gitlab::Serializer::Pagination::InvalidResourceError)
end
end
end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment