Skip to content

Instantly share code, notes, and snippets.

@robhurring
Created April 14, 2015 21:32
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 robhurring/3b86d75efd9137c582b3 to your computer and use it in GitHub Desktop.
Save robhurring/3b86d75efd9137c582b3 to your computer and use it in GitHub Desktop.
RSpec ActiveRecord model save and creation reporting
# ./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