Blog
Parameterized Test Groups with RSpec shared_examples and the args Hash
RSpec's shared_examples with an args hash lets you parameterize and reuse test groups across contexts, keeping suites DRY while preserving scope and integration with subject, let, and before.
Published by Tasadduq Burney
09 Mar 2026, 21:14 UTC
2 min25.9K views0

When you have multiple test contexts that validate the same behavior--say, a user authentication flow across different roles--copy-pasting example blocks becomes the default. It works, but every change ripples through dozens of files, and failures point to the duplication rather than the code.
Declaring a shared example
In RSpec, a shared example is defined withshared_examples :name. The block inside defines expectations that can reference subject, let, and before hooks from the including context, because RSpec preserves variable scope rather than cloning it.
shared_examples :a_valid_record do |args|
it 'validates that #{args[:field]} is present' do
expect(subject.send(args[:field])).to be_present
end
Including with arguments
Pass a hash of values when you invoke the shared block:include_examples :a_valid_record, field: :email. Inside the shared block, the args hash contains those keys, allowing you to parameterize the test without duplicating the example definition.
describe User do
include_examples :a_valid_record, field: :email
include_examples :a_valid_record, field: :username
end
What happens inside
Because the shared block runs in the context of the includingdescribe, any let or subject definitions available at the call site are accessible. If the shared block defines its own let, it stays local to that block and does not leak outward.
Common pitfalls
- Argument type mismatches. Passing the wrong key or type may produce a cryptic error such as undefined method or no receiver given, especially when the shared block expects a specific method call on subject.
- Reduced test granularity. When many expectations live inside a single shared block, a single failure can point to the block rather than the specific scenario, making it harder to pinpoint the root cause.
Verifying the setup
To confirm a shared example propagates correctly, run:rspec spec/models/user_spec.rb
Then modify the shared block--add a new it block, for instance--and run the command again. If the new example appears in the output for each including context, the reference linkage is active.
To isolate a failure, add a descriptive description to the it call, or use next_failure to step through the first failing example.
| Check | Expected |
|---|---|
| Shared example runs in including context | args[:field] resolves to the passed value |
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.