Class: Matchi::RaiseException

Inherits:
Object
  • Object
show all
Defined in:
lib/matchi/raise_exception.rb

Overview

*Expecting errors* matcher.

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ RaiseException

Initialize the matcher with a descendant of class Exception.

Examples:

require "matchi/raise_exception"

Matchi::RaiseException.new(NameError)

Parameters:

  • expected (Exception, #to_s)

    The expected exception name.

Raises:

  • (::ArgumentError)


14
15
16
17
18
19
20
# File 'lib/matchi/raise_exception.rb', line 14

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

Boolean comparison between the actual value and the expected value.

Examples:

require "matchi/raise_exception"

matcher = Matchi::RaiseException.new(NameError)
matcher.match? { Boom } # => true

Yield Returns:

  • (#object_id)

    The actual value to compare to the expected one.

Returns:

  • (Boolean)

    Comparison between actual and expected values.

Raises:

  • (::ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/matchi/raise_exception.rb', line 34

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 # Checks if the class of the thrown exception is klass or one of its subclasses
  end
end

#to_sString

Returns a string representing the matcher.

Returns:

  • (String)

    a human-readable description of the matcher



51
52
53
# File 'lib/matchi/raise_exception.rb', line 51

def to_s
  "raise exception #{@expected}"
end