Testing: shared examples
This course covers RSpec shared examples, starting from duplication in this app's request specs. A login-redirect assertion appears, typed by hand, in several files. RSpec's installed source shows how shared_examples stores a named block for later evaluation. It also shows how it_behaves_like wraps that block in a nested example group, while include_examples evaluates it flat in the current group. Later lessons cover arguments, customization blocks, an admin-only guard that has drifted, and a plain-Ruby challenge that builds a miniature registry.
What you'll learn
- ✓How shared_examples stores a named block and how scope decides where it can be found
- ✓How it_behaves_like creates a nested example group labeled "behaves like"
- ✓How include_examples and include_context evaluate shared content directly in the current group
- ✓Passing arguments and a customization block into a shared example
- ✓Finding duplicated assertions in a spec suite, including ones that have drifted apart
- ✓The ArgumentError raised when a shared example name is not registered
The duplication this app's spec suite already has
spec/requests/execution_spec.rb:
Read the full lesson free →Curriculum
7 lessonsThe duplication this app's spec suite already has
Five request specs repeat the same login-redirect assertion by hand, and the suite never uses shared_examples.
shared_examples defines reusable spec content once
shared_examples stores a named block for later evaluation, with scoping rules and two aliases for the same method.
it_behaves_like creates a nested context
RSpec's source shows it_behaves_like wrapping shared content in a new nested group labeled "behaves like".
include_examples flattens content into the current group
include_examples and include_context evaluate the shared block directly in the current group, adding no nesting.
Passing arguments and blocks into a shared example
An admin-only guard repeated in four files shows how arguments and blocks reach a shared example.
Where this app's spec suite would benefit
A survey of where shared examples fit this suite, what stays out of scope, and the missing-name error.
Putting it together: name it once, reuse it by name
A recap of the mental model and a plain-Ruby challenge that builds a miniature shared example registry.