assert_queries_match(match, count: nil, include_schema: false, &block)
public
Asserts that the SQL queries executed in the given block match expected
pattern.
assert_queries_match(/LIMIT \?/, count: 1) { Post.first }
assert_queries_match(/LIMIT \?/) { Post.first }
If the :include_schema option is provided, any queries (including
schema related) that match the matcher are considered.
assert_queries_match(/FROM pg_attribute/i, include_schema: true) { Post.columns }
# File activerecord/lib/active_record/testing/query_assertions.rb, line 59
def assert_queries_match(match, count: nil, include_schema: false, &block)
ActiveRecord::Base.lease_connection.materialize_transactions
counter = SQLCounter.new
ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do
result = _assert_nothing_raised_or_warn("assert_queries_match", &block)
queries = include_schema ? counter.log_all : counter.log
matched_queries = queries.select { |query| match === query }
if count
assert_equal count, matched_queries.size, "#{matched_queries.size} instead of #{count} queries were executed.#{queries.empty? ? '' : "\nQueries:\n#{queries.join("\n")}"}"
else
assert_operator matched_queries.size, :>=, 1, "1 or more queries expected, but none were executed.#{queries.empty? ? '' : "\nQueries:\n#{queries.join("\n")}"}"
end
result
end
end