Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.