RSpec matchers: expect
This course covers RSpec expectations as this app's suite writes them. It starts with the expect(actual).to matcher wiring and its .not_to form. It then reads matchers from RSpec's installed source: eq compares with plain Ruby ==, include delegates to the value's own include?, and be_truthy follows Ruby's truthiness rule. The block form shows why change and raise_error need expect with a block. A field guide covers predicate matchers, have_http_status, redirect_to, contain_exactly and chaining with .and. A final lesson ties the matchers together.
What you'll learn
- ✓How expect, .to and .not_to connect a value to a matcher
- ✓Why eq uses plain Ruby == and include delegates to include?
- ✓How be_truthy, be_falsey and be_nil follow Ruby's truthiness
- ✓Why change and raise_error need the block form of expect
- ✓How be_xxx predicate matchers and rspec-rails request matchers work
- ✓How to chain matchers with .and and use contain_exactly
expect(actual).to matcher: wrapping a value, describing what it should be
The course right before this one, RSpec: describe/context/it, showed the outer shape: describe, context and it, the blocks that organize a test and name what it checks. Inside every it block sits the assertion itself, and this app's spec/services/identity/account_update_service_spec.rb has a clean…
Read the full lesson free →Curriculum
7 lessonsexpect(actual).to matcher: wrapping a value, describing what it should be
How expect wraps the actual value, how a matcher holds the rule, and how .not_to flips the result.
eq: comparing with plain Ruby ==, read from RSpec's source
Why eq runs plain Ruby ==, and how that behaves for strings and ActiveRecord objects.
include: delegating to the #include? on the actual value
How include delegates to the value's own include?, shown on an Array and a String, plus chaining with .and.
be_truthy, be_falsey, be_nil: Ruby's truthiness, and a trap this app's suite avoids
How be_truthy, be_falsey and be_nil follow Ruby's truthiness, and why eq(true) fails on authenticate.
The block form: change and raise_error, and why they need a block
Why change and raise_error need expect with a block, plus the not_to raise_error and not_to change forms.
A field guide: this app's predicate matchers, request matchers, and chaining
Dynamic be_xxx predicate matchers, rspec-rails request matchers, contain_exactly, and chaining matchers with .and or .or.
Putting it together: reading a matcher, choosing the right one
A review of how each matcher delegates to a plain check, and how to choose one by its question.