Module: RSpecQueryCounter

Defined in:
lib/rspec_query_counter.rb,
lib/rspec_query_counter/counter.rb,
lib/rspec_query_counter/version.rb

Defined Under Namespace

Modules: Counter, Version

Class Method Summary collapse

Class Method Details

.counter_function(counter) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/rspec_query_counter.rb', line 42

def counter_function(counter)
  lambda do |_name, _started, _finished, _unique_id, payload|
    unless ["CACHE", "SCHEMA"].include?(payload[:name])
      counter.increment_total_count
      query_type = RSpecQueryCounter.query_type(payload[:name])
      counter.increment_query_type_count(query_type)
    end
  end
end

.presence(value) ⇒ Object



52
53
54
55
# File 'lib/rspec_query_counter.rb', line 52

def presence(value)
  return nil if value.nil? || value.empty?
  return value
end


33
34
35
36
37
38
39
40
# File 'lib/rspec_query_counter.rb', line 33

def print_results(counter)
  puts "\nTotal number of database queries: #{counter.total_query_count}"

  puts "Queries by type:"
  counter.query_type_count.each do |type, count|
    puts "#{type}: #{count}"
  end
end

.query_type(payload_name) ⇒ Object



27
28
29
30
31
# File 'lib/rspec_query_counter.rb', line 27

def query_type(payload_name)
  RSpecQueryCounter.presence(payload_name&.split(" ")&.drop(1)&.join(" ")) ||
    RSpecQueryCounter.presence(payload_name) ||
    "Unknown"
end

.setup(config) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rspec_query_counter.rb', line 7

def setup(config)
  counter = RSpecQueryCounter::Counter

  config.before(:suite) do
    counter.reset_counter!
  end

  config.around(:each) do |example|
    counter_f = RSpecQueryCounter.counter_function(counter)
    ActiveSupport::Notifications.subscribed(counter_f, "sql.active_record") do
      example.run
    end
  end

  config.after(:suite) do
    RSpecQueryCounter.print_results(counter)
    counter.reset_counter!
  end
end