0
0
Rubyprogramming~10 mins

RSpec expectations and matchers in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - RSpec expectations and matchers
Start Test
Set expectation
Run code under test
Compare actual vs expected
Continue
End Test
The test sets an expectation, runs code, compares actual and expected results, then passes or fails.
Execution Sample
Ruby
expect(5 + 3).to eq(8)
expect('ruby').to include('rub')
expect([1,2,3]).not_to be_empty
This code checks if 5+3 equals 8, if 'ruby' includes 'rub', and if the array is not empty.
Execution Table
StepExpectationActual ValueMatcherResultPass/Fail
1expect(5 + 3).to eq(8)8eq(8)8 == 8Pass
2expect('ruby').to include('rub')'ruby'include('rub')'ruby' includes 'rub'Pass
3expect([1,2,3]).not_to be_empty[1,2,3]not_to be_emptyArray is not emptyPass
💡 All expectations passed, test completes successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
actual_valuenil8'ruby'[1,2,3][1,2,3]
expectation_resultnilPassPassPassPass
Key Moments - 2 Insights
Why does expect(5 + 3).to eq(8) pass even though 5 + 3 is an expression?
The expression 5 + 3 is evaluated first to 8, then compared to 8 using eq matcher, so it passes as shown in execution_table step 1.
What does 'not_to be_empty' mean in the third expectation?
'not_to be_empty' checks that the array is NOT empty. Since [1,2,3] has elements, it passes as shown in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the actual value checked in step 2?
A8
B'ruby'
C'rub'
D[1,2,3]
💡 Hint
Check the 'Actual Value' column in execution_table row 2.
At which step does the matcher check that the array is not empty?
AStep 1
BStep 2
CStep 3
DNone
💡 Hint
Look at the 'Matcher' column in execution_table for step 3.
If expect(5 + 3).to eq(9) was used instead, what would happen in the execution table?
AStep 1 would show Fail
BStep 1 would show Pass
CStep 2 would show Fail
DNo change
💡 Hint
Compare actual value 8 with expected 9 in step 1's 'Result' column.
Concept Snapshot
RSpec expectations check if code results match what we want.
Use expect(actual).to matcher(expected) for positive checks.
Use expect(actual).not_to matcher for negative checks.
Common matchers: eq, include, be_empty.
Tests pass if actual matches expected, else fail.
Full Transcript
RSpec expectations and matchers let us write tests that check if code behaves as expected. We write expect statements with actual values and matchers to compare them. For example, expect(5 + 3).to eq(8) checks if 5 plus 3 equals 8. The test runs the code, compares actual and expected, and passes or fails accordingly. Matchers like eq check equality, include checks if a string contains a substring, and be_empty checks if a collection is empty. Using not_to reverses the check. The execution table shows each step's actual value, matcher used, and result. This helps beginners see how tests run step-by-step.