Skip to content

Instantly share code, notes, and snippets.

@anolson
Last active March 21, 2020 02:53
Show Gist options
  • Save anolson/40d4b7f6a2c72e488e6501eb289b1858 to your computer and use it in GitHub Desktop.
Save anolson/40d4b7f6a2c72e488e6501eb289b1858 to your computer and use it in GitHub Desktop.
Profile ActiveRecord queries with RSpec
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 unless operation.present?
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:"
sorted = Thread.current[:query_counter].sort_by { |location, count| count }.reverse
sorted.each do |location, count|
puts “#{count}: #{location}”
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment