Skip to content

Instantly share code, notes, and snippets.

@bbugh
Forked from anolson/spec_helper.rb
Last active September 14, 2017 20:25
Show Gist options
  • Save bbugh/1508641875bd7521b14014e4b38bf4d5 to your computer and use it in GitHub Desktop.
Save bbugh/1508641875bd7521b14014e4b38bf4d5 to your computer and use it in GitHub Desktop.
Profile ActiveRecord queries, output Markdown table of counts
# Originally referenced from https://medium.com/treehouse-engineering/continous-improvements-4741fc3c7daa
RSpec.configure do |config|
config.before(:suite) do
Thread.current[:query_counter] = Hash.new(0)
end
config.around(:example) do |procsy|
callback = lambda do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
sql = event.payload[:sql].to_s.strip
operation = sql.split(' ', 2).first.to_s.downcase
next if operation.blank?
next if event.payload[:name] == "SCHEMA"
next if event.payload[:name].nil?
Thread.current[:query_counter][procsy.location] += 1
end
ActiveSupport::Notifications.subscribed(callback, "sql.active_record") { procsy.run }
end
config.after(:suite) do
puts
puts "ActiveRecord queries performed:\n"
sorted = Thread.current[:query_counter].sort_by { |_location, count| count }.reverse
puts "| Location | Queries |"
puts "| -------- | ------- |"
sorted.each do |location, count|
puts "| #{location} | #{count} |"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment