Define custom RSpec matcher
11 March 2022 (Updated 24 April 2022)
On this page
Example use case
Suppose you’re writing a feature test and want to assert that a given route requires authentication. More specifically, you want to test that on visiting a protected route, two things happen:
- The current path is the login path.
- An error message is displayed.
You can do this using the default Capybara matchers:
That doesn’t read bad but this is a test that’ll probably be repeated several times so let’s try and make it more succint and expressive:
The custom matcher here is require_authentication
.
How to define the custom matcher
Create a file spec/support/custom_matchers.rb
, make sure this file from your rails_helper.rb
, and set its contents to:
This matcher can also be rewritten to take a block instead. See this post.
Sources
Tagged:
Rails testing
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment