RSpec is een Behavior-Driven Development (BDD) testtool voor Ruby.
Basis spec-structuur
RSpec.describe Calculator do
let(:calculator) { Calculator.new }
describe "#add" do
context "when adding positive numbers" do
it "returns the arithmetic sum" do
expect(calculator.add(2, 3)).to eq(5)
end
end
context "when given invalid input" do
it "raises an ArgumentError" do
expect { calculator.add(2, "x") }.to raise_error(ArgumentError)
end
end
end
end
Belangrijke matchers
# Gelijkheid
expect(actual).to eq(expected) # Waardegelijkheid (==)
expect(actual).to be(expected) # Objectidentiteit (equal?)
# Waarheidswaarden & Predikaten
expect(actual).to be_truthy
expect(actual).to be_nil
expect(user).to be_active # Roept user.active? aan
# Collecties
expect(list).to include("ruby")
expect(list).to match_array([1, 2]) # Zelfde elementen ongeacht volgorde
expect(list).to be_empty
# Vergelijkingen
expect(value).to be > 10
expect(value).to be_between(1, 100).inclusive
# Fouten & Uitzonderingen
expect { risky_call }.to raise_error(StandardError, /message/)
expect { safe_call }.not_to raise_error
Mocks & Stubs (rspec-mocks)
# Methode-stubbing
allow(user).to receive(:name).and_return("Alice")
# Verwachting bij methode-aanroep
expect(notifier).to receive(:send_email).with("[email protected]").once
# Double (mock-object)
mock_service = double("PaymentService", charge: true)