summaryrefslogtreecommitdiff
path: root/spec/support/shared_examples/serializers/environment_serializer_shared_examples.rb
blob: 87a330604353e93cf4078c45033ee75b2def7193 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true
RSpec.shared_examples 'avoid N+1 on environments serialization' do |ee: false|
  # Investigating in https://gitlab.com/gitlab-org/gitlab/-/issues/353209
  let(:query_threshold) { 1 + (ee ? 4 : 0) }

  it 'avoids N+1 database queries with grouping', :request_store do
    create_environment_with_associations(project)

    control = ActiveRecord::QueryRecorder.new { serialize(grouping: true) }

    create_environment_with_associations(project)
    create_environment_with_associations(project)

    expect { serialize(grouping: true) }
      .not_to exceed_query_limit(control.count)
      .with_threshold(query_threshold)
  end

  it 'avoids N+1 database queries without grouping', :request_store do
    create_environment_with_associations(project)

    control = ActiveRecord::QueryRecorder.new { serialize(grouping: false) }

    create_environment_with_associations(project)
    create_environment_with_associations(project)

    expect { serialize(grouping: false) }
      .not_to exceed_query_limit(control.count)
      .with_threshold(query_threshold)
  end

  it 'does not preload for environments that does not exist in the page', :request_store do
    create_environment_with_associations(project)

    first_page_query = ActiveRecord::QueryRecorder.new do
      serialize(grouping: false, query: { page: 1, per_page: 1 } )
    end

    second_page_query = ActiveRecord::QueryRecorder.new do
      serialize(grouping: false, query: { page: 2, per_page: 1 } )
    end

    expect(second_page_query.count).to be < first_page_query.count
  end

  def serialize(grouping:, query: nil)
    query ||= { page: 1, per_page: 20 }
    request = double(url: "#{Gitlab.config.gitlab.url}:8080/api/v4/projects?#{query.to_query}", query_parameters: query)

    EnvironmentSerializer.new(current_user: user, project: project).yield_self do |serializer|
      serializer.within_folders if grouping
      serializer.with_pagination(request, spy('response'))
      serializer.represent(Environment.where(project: project))
    end
  end
end