Skip to content

Instantly share code, notes, and snippets.

@janpaul123
Last active December 27, 2017 01:03
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 janpaul123/618a0ce08f88e8ce105f4916c75ec522 to your computer and use it in GitHub Desktop.
Save janpaul123/618a0ce08f88e8ce105f4916c75ec522 to your computer and use it in GitHub Desktop.
Test helper for changing counts
module ModelsHelper
# Expects that only the passed in models have counts that change. For this we
# look at all ActiveRecord models, and store their counts.
#
# Example: `expect_only_counts_changing(Trip: -1) { Trip.first.delete }`
#
# This gives stronger guarantees against future models being affected
# unexpectedly by other parts of the code base.
def expect_only_counts_changing(expected_changes)
previous_counts = ModelsHelper.counts
yield
new_counts = ModelsHelper.counts
changes = new_counts.map do |name, count|
change = count - previous_counts[name]
[name, change] unless change.zero?
end.compact.to_h
expect(changes).to eq(expected_changes)
end
# TODO: update all this with counts that you care about in your application.
EXCLUDED_CLASSES = [PaperTrail::Version, PaperTrail::VersionAssociation].freeze
def self.counts
Rails.application.eager_load!
models = ActiveRecord::Base.descendants - EXCLUDED_CLASSES
models.map { |model| [model.name.to_sym, model.count] }.to_h
end
end
RSpec.configure do |config|
config.include ModelsHelper
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment