Testing mastery: matchers
This course looks at RSpec matchers through a Rails suite of 204 spec files that has no custom matchers and no shared examples. It covers what a matcher does, how to read a failure message, and which built-in, Rails-aware and shoulda-matchers fit common assertions. It then shows how to write custom matchers, how to use shared examples and shared contexts, and how to choose between factories, helpers and matchers. The last lesson proposes three extractions for this suite and explains why to stop there.
What you'll learn
- ✓How a matcher decides a match and explains a failure
- ✓Why the matcher should receive the value, not a boolean derived from it
- ✓Choosing between eq, contain_exactly, change, raise_error and have_attributes
- ✓Writing custom matchers with match, chain, both failure messages and description
- ✓Using shared examples and shared contexts with it_behaves_like and include_context
- ✓When to use factories, helpers, matchers or shared examples, and when to keep duplication
The matchers this suite already uses
This repository has 204 spec files: models, queries, requests, services, policies, helpers, jobs and mailers. Reading a few of them shows what the suite is already doing well, and one thing it is not doing at all.
Read the full lesson free →Curriculum
7 lessonsThe matchers this suite already uses
Defines a matcher, reviews the choices in this suite's model spec, and notes what the suite lacks.
Reading a failure message
Compares four failure messages for the same bug and explains why the matcher should receive the value itself.
The matchers worth knowing
Surveys useful matchers for equality, collections, change, errors, attributes, composition and Rails responses and jobs.
Custom matchers
Shows how to write a custom matcher with both failure messages, and when a built-in or predicate fits better.
Shared examples and shared contexts
Explains shared examples and shared contexts, it_behaves_like versus include_examples, and parameterizing with arguments or blocks.
Matchers, helpers and factories
Sets out when to use factories, helpers, matchers or shared examples, and the cost of too much abstraction.
Putting it together: what to extract
Proposes three extractions in order of value: an owned-resource example, a query-object example and a CSP matcher.