Created
November 10, 2011 00:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put it in your
spec/support
directory to get it working.