Skip to content

Commit

Permalink
Merge pull request rails#50334 from yykamei/add_doc_for_assert_queries
Browse files Browse the repository at this point in the history
Add doc for `assert_queries` and `assert_no_queries`
  • Loading branch information
byroot authored Dec 14, 2023
2 parents 970126e + ccc512f commit 9517841
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
20 changes: 15 additions & 5 deletions activerecord/lib/active_record/testing/query_assertions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,29 @@
module ActiveRecord
module Assertions
module QueryAssertions
# Asserts that the number of SQL queries executed in the given block matches the expected count.
#
# assert_queries(1) { Post.first }
#
# If the +:matcher+ option is provided, only queries that match the matcher are counted.
#
# assert_queries(1, matcher: /LIMIT \?/) { Post.first }
#
def assert_queries(expected_count, matcher: nil, &block)
ActiveRecord::Base.connection.materialize_transactions

queries = []
ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|
callback = lambda do |*, payload|
queries << payload[:sql] if %w[ SCHEMA TRANSACTION ].exclude?(payload[:name]) && (matcher.nil? || payload[:sql].match(matcher))
end

result = _assert_nothing_raised_or_warn("assert_queries", &block)
assert_equal expected_count, queries.size, "#{queries.size} instead of #{expected_count} queries were executed. Queries: #{queries.join("\n\n")}"
result
ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
result = _assert_nothing_raised_or_warn("assert_queries", &block)
assert_equal expected_count, queries.size, "#{queries.size} instead of #{expected_count} queries were executed. Queries: #{queries.join("\n\n")}"
result
end
end

# Asserts that no SQL queries are executed in the given block.
def assert_no_queries(&block)
assert_queries(0, &block)
end
Expand Down
23 changes: 16 additions & 7 deletions activerecord/test/cases/assertions/query_assertions_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,24 @@ def test_assert_queries
}
assert_match(/1 instead of 0 queries/, error.message)
end
end

def test_assert_no_queries
assert_no_queries { Post.none }
def test_assert_queries_with_matcher
error = assert_raises(Minitest::Assertion) {
assert_queries(1, matcher: /WHERE "posts"."id" = \? LIMIT \?/) do
Post.where(id: 1).first
end
}
assert_match(/0 instead of 1 queries/, error.message)
end

def test_assert_no_queries
assert_no_queries { Post.none }

error = assert_raises(Minitest::Assertion) {
assert_no_queries { Post.first }
}
assert_match(/1 .* instead of 2/, error.message)
error = assert_raises(Minitest::Assertion) {
assert_no_queries { Post.first }
}
assert_match(/1 instead of 0/, error.message)
end
end
end
end

0 comments on commit 9517841

Please sign in to comment.