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.
expect(5 + 3).to eq(8) expect('ruby').to include('rub') expect([1,2,3]).not_to be_empty
| Step | Expectation | Actual Value | Matcher | Result | Pass/Fail |
|---|---|---|---|---|---|
| 1 | expect(5 + 3).to eq(8) | 8 | eq(8) | 8 == 8 | Pass |
| 2 | expect('ruby').to include('rub') | 'ruby' | include('rub') | 'ruby' includes 'rub' | Pass |
| 3 | expect([1,2,3]).not_to be_empty | [1,2,3] | not_to be_empty | Array is not empty | Pass |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| actual_value | nil | 8 | 'ruby' | [1,2,3] | [1,2,3] |
| expectation_result | nil | Pass | Pass | Pass | Pass |
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.
expect(value).to eq(5) check for?eq matchereq matcher tests for equality between the expected and actual values.expect(value).to eq(5) means the test expects value to be exactly 5.value is equal to 5. -> Option Dinclude matcher checks if a collection contains a specific element.expect(array).to include(3) is the correct syntax to check if 3 is in the array.describe 'Number test' do
it 'checks if number is odd' do
number = 7
expect(number.odd?).to be true
end
endnumber is set to 7, which is an odd number.expect(number.odd?).to be true checks if number.odd? returns true, which it does for 7.expect(user.name).to eq nil
eq nil works, the preferred matcher for nil is be_nil for clarity and style.expect(user.name).to be_nil is clearer and idiomatic in RSpec.be_nil matcher instead of eq nil. -> Option Ccalculate returns a value greater than 10 but less than 20. Which RSpec expectation correctly checks this?expect(calculate).to be > 10 and be < 20 is invalid syntax; correct chaining uses (be > 10).and(be < 20).be_between is not a built-in RSpec matcher.expect(calculate).to satisfy { |v| v > 10 && v < 20 } correctly checks the condition using a standard flexible matcher.Pass the test and this pattern moves unknown