Skip to content

Instantly share code, notes, and snippets.

@jakeonrails
Last active June 22, 2016 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakeonrails/a672674b6fd85906172db866a8437eda to your computer and use it in GitHub Desktop.
Save jakeonrails/a672674b6fd85906172db866a8437eda to your computer and use it in GitHub Desktop.
require 'awesome_print'
# Put this file into your spec/support directory in order to have RSpec automatically report
# on the total number of database records created during a run of your test suite.
class ActiveRecordInsertCountReport
include Singleton
def subscribe_to_notifications
ActiveSupport::Notifications.subscribe('sql.active_record') do |*args|
name, start, ending, transaction_id, payload = args
table_name = payload[:sql][/insert into "(.+?)"/i, 1]
insert_counts[table_name] += 1 if table_name
end
end
def print_report
totals = Hash[insert_counts.to_a.sort_by(&:last).reverse]
totals['-' * 20] = 0
totals["Total records created"] = totals.values.sum
ap totals
end
def insert_counts
@insert_counts ||= Hash.new(0)
end
class << self
delegate :subscribe_to_notifications, to: :instance
delegate :print_report, to: :instance
end
end
RSpec.configure do |config|
config.before(:all) do
ActiveRecordInsertCountReport.subscribe_to_notifications
end
config.after(:all) do |x|
ActiveRecordInsertCountReport.print_report
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment