Refactoring to Single-Assertion Specs
Learn about the single-assertion styles, RSpec-given gem, and aggregating failures.
RSpec single-assertion style
There’s nothing to refactor in the code right now, but we have a series of tests with a common setup and a common set of assertions. This duplication can be managed in RSpec in a few different ways, including letting it stay the way it is if we find the tests quite readable in their current structure.
Also, there’s a coding style that prefers to have specs that contain just a single assertion. By default, RSpec ends the spec when the first expectation fails. This means that if there are any expectations later in the spec, we don’t know whether they are correct. Sometimes this can lead to the tests giving an inaccurate sense of the status of the code.
The let
single-assertion style
The let
single-assertion style looks a little different than the testing style we’ve seen so far. It often takes advantage of the lazy nature of RSpec’s let
to specify the common action and allows each test to specify an input to the action. Here’s an example:
Get hands-on with 1200+ tech skills courses.