Skip to content

SQL queries matcher support #2817

Open
Open
@hugopeixoto

Description

@hugopeixoto

Rails 7 added support for a few query assertions:

assert_queries_count(1) { Post.first }
assert_queries_count { Post.first }
assert_queries_count(1, include_schema: true) { Post.columns }

assert_no_queries { post.comments }
assert_no_queries(include_schema: true) { Post.columns }

assert_queries_match(/LIMIT \?/, count: 1) { Post.first }
assert_queries_match(/LIMIT \?/) { Post.first }
assert_queries_match(/FROM pg_attribute/i, include_schema: true) { Post.columns }

assert_no_queries_match(/SELECT/i) { post.comments }
assert_no_queries_match(/FROM pg_attribute/i, include_schema: true) { Post.columns }

Does an equivalent matcher belong in rspec-rails?

I've found these rails assertions useful to ensure performance issues (like N+1 queries) don't appear and to make regression tests for when they do.

In projects that use rspec-rails, a matcher that allows to test for the number of queries executed would be helpful.

I have implemented a custom matcher that supports a subset of these:

expect { Post.first }.to execute_queries(1)
expect { Post.first }.to execute_no_queries

These could be expanded to support matching, no count, and include_schema:

expect { Post.first }.to execute_queries
expect { Post.first }.to execute_queries(1).matching(/LIMIT \?/)
expect { Post.first }.to execute_no_queries.including_schema

I'm working on making a PR to rspec-rails to support these, opening an issue now to iterate on the syntax and to check if it belongs here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions