Skip to content

Instantly share code, notes, and snippets.

@christoomey
Created May 19, 2020 14:22
Show Gist options
  • Save christoomey/9d1cc5f1737b722cb7ec0566fe3d1729 to your computer and use it in GitHub Desktop.
Save christoomey/9d1cc5f1737b722cb7ec0566fe3d1729 to your computer and use it in GitHub Desktop.
SQL Queries Summaries helper
module SqlQueryCountingHelpers
# This helper can be used to instrument a segment of test code to analyze the
# SQL queries being executed for that portion of the code path.
#
# It's intended to be used around specific portions of a spec rather than an
# entire spec as the FactoryBot usage adds a good amount of noise to the SQL
# analysis due to the many objects & associations created.
#
# Usage example (using spec/requests/api/v1/projects_spec.rb):
#
# ``` rb
# with_sql_count do
# get '/api/v1/projects', headers: auth_headers(user)
# end
# ```
#
# which will produce output like:
#
# Get /api/v1/projects
# User Load
# User Load
#
# Project Load
# Project Load
# Area Load
# SharedImage Load
# Action Load
# SCHEMA
# DailyReminder Load
# SCHEMA
# SCHEMA
# ==================================================
# There were 14 SQL calls
# --------------------------------------------------
#
# You can then tweak the implementation and see how the structure and count of
# SQL queries changes
def with_sql_count(&block)
sql_count = 0
callback = ->(*args) do
event = ActiveSupport::Notifications::Event.new *args
puts event.payload[:name].presence || event.payload[:sql].first(50)
sql_count +=1
end
ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
yield
end
puts <<~EOM
#{'='*50}
There were #{sql_count} SQL calls
#{'-'*50}
EOM
end
end
RSpec.configure { |config| config.include SqlQueryCountingHelpers }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment