Repository navigation
Expecting errors example
Cyril Kato edited this page Nov 1, 2026
·
1 revision
raise_exception takes the class of the exception, or its name, and an expected message: a String to equal, or a Regexp to match. It judges what the block of expect { … }, is_expected or its raises; an exception of another class is an error, not a failure.
require "r_spec"
RSpec.describe "an error" do
it { expect { raise "boom" }.to raise_exception RuntimeError }
it { expect { raise "boom" }.to raise_exception RuntimeError, "boom" }
it { expect { raise "boom" }.to raise_exception RuntimeError, /oo/ }
it { expect { raise ArgumentError }.to raise_exception StandardError }
it { expect { :quiet }.not_to raise_exception StandardError }
it { expect { raise "boom" }.not_to raise_exception ArgumentError }
end$ ruby spec/errors_spec.rb
spec/errors_spec.rb:4: Success: expected #<RuntimeError: boom> to raise exception RuntimeError
spec/errors_spec.rb:5: Success: expected #<RuntimeError: boom> to raise exception RuntimeError with message "boom"
spec/errors_spec.rb:6: Success: expected #<RuntimeError: boom> to raise exception RuntimeError with message /oo/
spec/errors_spec.rb:7: Success: expected #<ArgumentError: ArgumentError> to raise exception StandardError
spec/errors_spec.rb:8: Success: expected :quiet not to raise exception StandardError
spec/errors_spec.rb:9: Success: expected #<RuntimeError: boom> not to raise exception ArgumentError