File tree Expand file tree Collapse file tree 2 files changed +31
-12
lines changed
lib/active_record/testing Expand file tree Collapse file tree 2 files changed +31
-12
lines changed Original file line number Diff line number Diff line change 3
3
module ActiveRecord
4
4
module Assertions
5
5
module QueryAssertions
6
+ # Asserts that the number of SQL queries executed in the given block matches the expected count.
7
+ #
8
+ # assert_queries(1) { Post.first }
9
+ #
10
+ # If the +:matcher+ option is provided, only queries that match the matcher are counted.
11
+ #
12
+ # assert_queries(1, matcher: /LIMIT \?/) { Post.first }
13
+ #
6
14
def assert_queries ( expected_count , matcher : nil , &block )
7
15
ActiveRecord ::Base . connection . materialize_transactions
8
16
9
17
queries = [ ]
10
- ActiveSupport :: Notifications . subscribe ( "sql.active_record" ) do |*, payload |
18
+ callback = lambda do |*, payload |
11
19
queries << payload [ :sql ] if %w[ SCHEMA TRANSACTION ] . exclude? ( payload [ :name ] ) && ( matcher . nil? || payload [ :sql ] . match ( matcher ) )
12
20
end
13
-
14
- result = _assert_nothing_raised_or_warn ( "assert_queries" , &block )
15
- assert_equal expected_count , queries . size , "#{ queries . size } instead of #{ expected_count } queries were executed. Queries: #{ queries . join ( "\n \n " ) } "
16
- result
21
+ ActiveSupport ::Notifications . subscribed ( callback , "sql.active_record" ) do
22
+ result = _assert_nothing_raised_or_warn ( "assert_queries" , &block )
23
+ assert_equal expected_count , queries . size , "#{ queries . size } instead of #{ expected_count } queries were executed. Queries: #{ queries . join ( "\n \n " ) } "
24
+ result
25
+ end
17
26
end
18
27
28
+ # Asserts that no SQL queries are executed in the given block.
19
29
def assert_no_queries ( &block )
20
30
assert_queries ( 0 , &block )
21
31
end
Original file line number Diff line number Diff line change @@ -22,15 +22,24 @@ def test_assert_queries
22
22
}
23
23
assert_match ( /1 instead of 0 queries/ , error . message )
24
24
end
25
- end
26
25
27
- def test_assert_no_queries
28
- assert_no_queries { Post . none }
26
+ def test_assert_queries_with_matcher
27
+ error = assert_raises ( Minitest ::Assertion ) {
28
+ assert_queries ( 1 , matcher : /WHERE "posts"."id" = \? LIMIT \? / ) do
29
+ Post . where ( id : 1 ) . first
30
+ end
31
+ }
32
+ assert_match ( /0 instead of 1 queries/ , error . message )
33
+ end
34
+
35
+ def test_assert_no_queries
36
+ assert_no_queries { Post . none }
29
37
30
- error = assert_raises ( Minitest ::Assertion ) {
31
- assert_no_queries { Post . first }
32
- }
33
- assert_match ( /1 .* instead of 2/ , error . message )
38
+ error = assert_raises ( Minitest ::Assertion ) {
39
+ assert_no_queries { Post . first }
40
+ }
41
+ assert_match ( /1 instead of 0/ , error . message )
42
+ end
34
43
end
35
44
end
36
45
end
You can’t perform that action at this time.
0 commit comments