class Given::Failure

Failure objects will raise the given exception whenever you try to send it any message.

Public Class Methods

capture(*exceptions) { || ... } click to toggle source

Evaluate a block. If an exception is raised, capture it in a Failure object. Explicitly listed exceptions are passed thru without capture.

   # File lib/given/failure.rb
12 def self.capture(*exceptions)
13   begin
14     yield
15   rescue *exceptions => ex
16     raise
17   rescue ::Exception => ex
18     new(ex)
19   end
20 end
new(exception) click to toggle source

Create a failure object that will rethrow the given exception whenever an undefined method is called.

   # File lib/given/failure.rb
24 def initialize(exception)
25   @exception = exception
26 end

Public Instance Methods

!=(other) click to toggle source

Failure objects may be compared for in-equality. If the comparison object is not a matcher, then the exception is re-raised.

   # File lib/given/failure.rb
45 def !=(other)
46   if failure_matcher?(other)
47     other.does_not_match?(self)
48   else
49     die
50   end
51 end
==(other) click to toggle source

Failure objects may be compared for equality. If the comparison object is not a matcher, then the exception is re-raised.

   # File lib/given/failure.rb
35 def ==(other)
36   if failure_matcher?(other)
37     other.matches?(self)
38   else
39     die
40   end
41 end
is_a?(klass) click to toggle source

Failure objects will respond to is_a?.

   # File lib/given/failure.rb
29 def is_a?(klass)
30   klass == Failure
31 end
method_missing(sym, *args, &block) click to toggle source

Most methods will just re-raise the captured exception.

   # File lib/given/failure.rb
54 def method_missing(sym, *args, &block)
55   die
56 end
must_raise(*args) click to toggle source

Minitest expectation method. Since Failure inherits from BasicObject, we need to add this method explicitly.

   # File lib/given/minitest/failure_must_raise.rb
 6 def must_raise(*args)
 7   ::Minitest::Spec.current.assert_raises(*args) do
 8     die
 9   end
10 end
respond_to?(method_symbol) click to toggle source

Report that we respond to a limited number of methods.

   # File lib/given/failure.rb
59 def respond_to?(method_symbol)
60   method_symbol == :call ||
61     method_symbol == :== ||
62     method_symbol == :!= ||
63     method_symbol == :is_a? ||
64     method_symbol == :to_bool
65 end

Private Instance Methods

die() click to toggle source

Re-raise the captured exception.

   # File lib/given/failure.rb
70 def die
71   ::Kernel.raise @exception
72 end
failure_matcher?(other) click to toggle source

Is the comparison object a failure matcher?

   # File lib/given/failure.rb
75 def failure_matcher?(other)
76   other.respond_to?(:matches?) && other.respond_to?(:does_not_match?)
77 end