Class: Matchi::RaiseException
- Inherits:
-
Object
- Object
- Matchi::RaiseException
- Defined in:
- lib/matchi/raise_exception.rb
Overview
Exception matcher that verifies if a block of code raises a specific exception.
This matcher ensures that code raises an expected exception by executing it within a controlled environment. It supports matching against specific exception classes and their subclasses, providing a reliable way to test error handling.
Instance Method Summary collapse
-
#initialize(expected) ⇒ RaiseException
constructor
Initialize the matcher with an exception class.
-
#match? { ... } ⇒ Boolean
Checks if the yielded block raises the expected exception.
-
#to_s ⇒ String
Returns a human-readable description of the matcher.
Constructor Details
#initialize(expected) ⇒ RaiseException
Initialize the matcher with an exception class.
57 58 59 60 61 62 63 |
# File 'lib/matchi/raise_exception.rb', line 57 def initialize(expected) @expected = String(expected) return if /\A[A-Z]/.match?(@expected) raise ::ArgumentError, "expected must start with an uppercase letter (got: #{@expected})" end |
Instance Method Details
#match? { ... } ⇒ Boolean
Checks if the yielded block raises the expected exception.
This method executes the provided block within a begin/rescue clause and verifies that it raises an exception of the expected type. It also handles inheritance, allowing subclasses of the expected exception to match.
93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/matchi/raise_exception.rb', line 93 def match? raise ::ArgumentError, "a block must be provided" unless block_given? klass = expected_class raise ::ArgumentError, "expected exception class must inherit from Exception" unless klass <= ::Exception begin yield false rescue ::Exception => e # rubocop:disable Lint/RescueException e.class <= klass end end |
#to_s ⇒ String
Returns a human-readable description of the matcher.
115 116 117 |
# File 'lib/matchi/raise_exception.rb', line 115 def to_s "raise exception #{@expected}" end |