summaryrefslogtreecommitdiff
path: root/spec/support/matchers/be_n_plus_1_query.rb
blob: bbfd1897f04d0cec9befb8939faeaf1303301f49 (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
57
58
59
60
61
62
# frozen_string_literal: true

module Nplus1QueryHelpers
  DEFAULT_THRESHOLD = 3

  def with_threshold(threshold)
    @threshold = threshold
    self
  end

  def for_query(query)
    @query = query
    self
  end

  def threshold
    @threshold || DEFAULT_THRESHOLD
  end

  def occurrences
    @occurrences ||=
      if @query
        recorder.occurrences.select { |recorded, count| recorded =~ @query }
      else
        recorder.occurrences
      end
  end

  def over_threshold
    occurrences.select do |recorded, count|
      count > threshold
    end
  end

  def recorder
    @recorder ||= ActiveRecord::QueryRecorder.new(&@subject_block)
  end

  def verify_count(&block)
    @subject_block = block
    over_threshold.present?
  end

  def failure_message
    log_message = over_threshold.to_yaml
    "The following queries are executed more than #{threshold} time(s):\n#{log_message}"
  end
end

RSpec::Matchers.define :be_n_plus_1_query do
  supports_block_expectations

  include Nplus1QueryHelpers

  match do |block|
    verify_count(&block)
  end

  failure_message_when_negated do |actual|
    failure_message
  end
end