Skip to content

Instantly share code, notes, and snippets.

@jakeonrails
Created November 10, 2011 00:02
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/1353611 to your computer and use it in GitHub Desktop.
Save jakeonrails/1353611 to your computer and use it in GitHub Desktop.
Spits out a report at the end of your tests on how many times each model was created
if Rails.application.config.report_model_creation_counts
class ReportModelCreationCounts < ActiveRecord::Observer
@@creates = Hash.new { |hash, key| hash[key] = 0 }
def after_create(record)
@@creates[record.class] += 1
end
def self.print_report
puts 'Your tests created the following objects:'
longest_key = @@creates.keys.max { |a, b| a.to_s.length <=> b.to_s.length }.to_s
report = @@creates.sort { |a,b| b[1] <=> a[1] } # sort in descending order
report.each do |klass, creations|
printf "%-#{longest_key.length}s %s\n", klass, creations if creations > 0
end
end
def self.all_models
models = ActiveRecord::Base.send(:descendants)
@@required ||= false
unless @@required
Dir.glob(Rails.root.to_s + '/app/models/**/*.rb').each do |file|
begin
klass = File.basename(file.gsub('/app/models/', '').gsub('/', '_'), '.rb').classify.constantize
rescue
require file
end
end
end
@@required = true
models = ActiveRecord::Base.send(:descendants).map(&:to_s).sort.map(&:constantize)
models.each do |model|
@@creates[model] = 0
end
end
observe all_models
end
ReportModelCreationCounts.instance
RSpec.configure do |config|
config.after(:suite) do
ReportModelCreationCounts.print_report
end
end
end
@jakeonrails
Copy link
Author

Put it in your spec/support directory to get it working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment