expect(actual).to matcher: wrapping a value, describing what it should be
An assertion from this app's suite
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 one:
it "updates the password when current password is correct" do
result = described_class.new(user, params).call
expect(result).to be_truthy
expect(user.reload.authenticate(new_password)).to be_truthy
end
expect(result) wraps result, the value the test produced, in an object RSpec builds for this purpose. .to be_truthy hands that object a matcher, be_truthy, which knows how to check whether the wrapped value is truthy. Two jobs, two objects: expect holds the actual value, and the matcher holds the rule it's checked against.
Why split it into two calls
A single method could take both at once, as in assert_truthy(result). RSpec splits them because the matcher (be_truthy, eq(5), include("x")) is a standalone object with its own logic, reusable anywhere expect is. expect(result).to be_truthy and expect(other_thing).to be_truthy go through the same be_truthy mechanics; only the wrapped value changes. The next five lessons read what each matcher checks from RSpec's installed source.
.to and .not_to, the same wiring in both directions
expect(...).to matcher passes when the matcher's check succeeds. expect(...).not_to matcher passes when it fails. This app's spec/models/identity/authentication_spec.rb uses the negative form:
expect(new_auth).not_to be_valid
Same expect, same matcher, be_valid, and one word flips which outcome counts as a pass. The matcher doesn't change between the two forms, only which side of its answer the test asserts.
What this course covers
Seven lessons, each checked against this app's spec files or RSpec's installed source. This lesson covers the expect/.to/.not_to wiring. Lesson 2 covers eq, the plain-equality matcher. Lesson 3 covers include on arrays, strings and hashes. Lesson 4 covers be_truthy/be_falsey/be_nil, and a case where the obvious-looking alternative, eq(true), fails. Lesson 5 covers the block form, expect { ... }.to change { ... } and expect { ... }.to raise_error(...), and why it needs a block at all. Lesson 6 is a field guide to the rest of this app's matchers, be_valid, have_http_status, redirect_to and be_empty, plus chaining two matchers with .and. Lesson 7 ends with a challenge: a small matcher dispatcher in plain Ruby.
Keep going with lesson 2
eq: comparing with plain Ruby ==, read from RSpec's source
Why eq runs plain Ruby ==, and how that behaves for strings and ActiveRecord objects.
A free account also gives you the quizzes, your progress and notes, and the discussion.