Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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