You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The gem defines matcher exceed_query_limit that takes maximum number of SQL requests to be made inside the block.
require"rspec-sqlimit"RSpec.describe"N+1 safety"doit"doesn't send unnecessary requests to db"doexpect{User.create}.not_toexceed_query_limit(1)endend
The above specification fails with the following description:
Failure/Error: expect { User.create }.not_to exceed_query_limit(1)
Expected to run maximum 1 queries
The following 3 queries were invoked:
1) begin transaction (0.045 ms)
2) INSERT INTO "users" DEFAULT VALUES (0.19 ms)
3) commit transaction (148.935 ms)
You can restrict the matcher using regex:
require"rspec-sqlimit"RSpec.describe"N+1 safety"doit"doesn't send unnecessary requests to db"doexpect{User.create}.not_toexceed_query_limit(1).with(/^INSERT/)endend
This time test passes.
When a specification with a restriction fails, you'll see an error as follows:
require"rspec-sqlimit"RSpec.describe"N+1 safety"doit"doesn't send unnecessary requests to db"doexpect{User.createname: "Joe"}.not_toexceed_query_limit(0).with(/^INSERT/)endend
Failure/Error: expect { User.create }.not_to exceed_query_limit(0).with(/INSERT/)
Expected to run maximum 0 queries that match (?-mix:INSERT)
The following 1 queries were invoked among others (see mark ->):
1) begin transaction (0.072 ms)
-> 2) INSERT INTO "users" ("name") VALUES (?); ["Joe"] (0.368 ms)
3) commit transaction (147.559 ms)
In the last example you can see that binded values are shown after the query following the Rails convention.
License
The gem is available as open source under the terms of the MIT License.
About
RSpec matcher to control SQL queries made by block of code