Skip to content

Instantly share code, notes, and snippets.

@jenny-codes
Last active March 9, 2020 00:17
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 jenny-codes/f641fcb4529a5c5b0a75113d8da24de0 to your computer and use it in GitHub Desktop.
Save jenny-codes/f641fcb4529a5c5b0a75113d8da24de0 to your computer and use it in GitHub Desktop.
Asserting the number of database queries or cache lookups performed for tests
require 'path/to/test_helper'
class ExampleTest
test 'this should trigger 1 database query' do
assert_db_queries(1) do
# ... code
end
end
end
class TestHelper
# Count SQL queries
# [optional]
# We record the actual queries, and print them out if the assertion fails.
# It enables us to see what extra queries we are invoking. Helps a lot with debugging.
def assert_db_queries(expected_hits, debug: false, &block)
actual_hits = 0
queries = []
counter_f = ->(_name, _started, _finished, _unique_id, payload) do
unless payload[:name].in? %w[CACHE SCHEMA]
queries << payload[:sql]
actual_hits += 1
end
end
ActiveSupport::Notifications.subscribed(counter_f, 'sql.active_record', &block)
actual_queries = "Queries performed:\n#{queries.join("\n")}"
puts actual_queries if debug
assert_equal expected_hits, actual_hits, actual_queries
end
def assert_cache_queries(expected_hits, debug: false, &block)
actual_hits = 0
queries = []
counter_f = ->(_name, _started, _finished, _unique_id, payload) do
if payload[:hit]
queries << payload[:key]
actual_hits += 1
end
end
ActiveSupport::Notifications.subscribed(counter_f, 'cache_read.active_support', &block)
actual_queries = "Queries performed:\n#{queries.join("\n")}"
puts actual_queries if debug
assert_equal expected_hits, actual_hits, actual_queries
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment