Created
April 14, 2015 21:32
-
-
Save robhurring/3b86d75efd9137c582b3 to your computer and use it in GitHub Desktop.
RSpec ActiveRecord model save and creation reporting
This file contains hidden or 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
# ./spec/support/save_tracker.rb | |
module SaveTracker | |
extend ActiveSupport::Concern | |
included do | |
class_attribute :_save_tracker_ | |
self.reset_save_tracker! | |
end | |
module ClassMethods | |
def reset_save_tracker! | |
self._save_tracker_ = Hash.new do |report, type| | |
report[type] = Hash.new{ |klass, count| klass[count] = 0 } | |
end | |
end | |
def output_save_stats(reporter) | |
tracker = self._save_tracker_ | |
[:create, :save].each do |type, color| | |
next if tracker[type].empty? | |
reporter.puts "\nModels #{type}d:" | |
tracker[type].each do |klass, count| | |
reporter.puts " #{klass}: #{count} times" | |
end | |
reporter.puts | |
end | |
end | |
end | |
def save(*) | |
type = new_record? ? :create : :save | |
self.class._save_tracker_[type][self.class.name] += 1 | |
super | |
end | |
end | |
ActiveRecord::Base.__send__(:include, SaveTracker) | |
# Add to RSpec config | |
RSpec.configure do |config| | |
config.before(:suite) do | |
ActiveRecord::Base.reset_save_tracker! | |
end | |
config.after(:suite) do | |
ActiveRecord::Base.output_save_stats($stderr) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment