Skip to content

Instantly share code, notes, and snippets.

@soffes
Created March 11, 2021 15:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soffes/ec8649c9e5dd57e268b9bf3f62d531d8 to your computer and use it in GitHub Desktop.
Save soffes/ec8649c9e5dd57e268b9bf3f62d531d8 to your computer and use it in GitHub Desktop.
Simple ActiveRecord query counter
class TestCase < ActiveSupport::TestCase
def setup
super
DatabaseCleaner.start
@queries = []
ActiveSupport::Notifications.subscribe('sql.active_record') do |_, _, _, _, payload|
@queries << payload[:sql] unless payload[:name].in? %w[CACHE SCHEMA]
end
end
def teardown
DatabaseCleaner.clean
super
end
def assert_query_count(expected_count)
before_count = 0
if block_given?
before_count = @queries.length
yield
end
actual_count = @queries.length - before_count
assert_equal expected_count, actual_count, @queries[before_count...].join("\n")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment