RSpec expectations let you check if your code works as you want. Matchers help describe what you expect.
0
0
RSpec expectations and matchers in Ruby
Introduction
When you want to test if a method returns the right value.
When you want to check if an object has a certain property.
When you want to verify if a block of code raises an error.
When you want to confirm that a value is included in a list.
When you want to test if two values are equal or not.
Syntax
Ruby
expect(actual_value).to matcher(expected_value) expect(actual_value).not_to matcher(expected_value)
expect() wraps the actual value you want to test.
to means you expect the matcher to be true; not_to means you expect it to be false.
Examples
Checks if 5 equals 5.
Ruby
expect(5).to eq(5)
Checks if the string 'hello' contains 'ell'.
Ruby
expect('hello').to include('ell')
Checks that the array does not include 4.
Ruby
expect([1, 2, 3]).not_to include(4)
Checks if the block raises a StandardError.
Ruby
expect { raise StandardError }.to raise_error(StandardError)Sample Program
This program tests simple math operations using RSpec expectations and matchers.
It checks addition, array inclusion, and error raising.
Ruby
require 'rspec/autorun' RSpec.describe 'Simple math' do it 'adds numbers correctly' do expect(2 + 3).to eq(5) end it 'does not equal wrong sum' do expect(2 + 2).not_to eq(5) end it 'includes element in array' do expect([1, 2, 3]).to include(2) end it 'raises error when dividing by zero' do expect { 1 / 0 }.to raise_error(ZeroDivisionError) end end
OutputSuccess
Important Notes
Matchers like eq, include, and raise_error are common and easy to use.
You can chain not_to to expect something NOT to happen.
RSpec output shows which tests passed or failed, helping you find problems quickly.
Summary
RSpec expectations check if your code behaves as expected.
Matchers describe the exact condition you want to test.
Use expect().to for positive checks and expect().not_to for negative checks.