Skip to content

Commit c51668d

Browse files
committed
Add Test::Unit::CoreAssertions#assert_raise_kind_of
Similar to `Test::Unit::assert_raise`, but allows sub classes too.
1 parent ae94fca commit c51668d

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

tool/lib/core_assertions.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,43 @@ def assert_raise_with_message(exception, expected, msg = nil, &block)
514514
ex
515515
end
516516

517+
# :call-seq:
518+
# assert_raise_kind_of(*args, &block)
519+
#
520+
#Tests if the given block raises one of the given exceptions or
521+
#sub exceptions of the given exceptions. If the last argument
522+
#is a String, it will be used as the error message.
523+
#
524+
# assert_raise do #Fails, no Exceptions are raised
525+
# end
526+
#
527+
# assert_raise SystemCallErr do
528+
# Dir.chdir(__FILE__) #Raises Errno::ENOTDIR, so assertion succeeds
529+
# end
530+
def assert_raise_kind_of(*exp, &b)
531+
case exp.last
532+
when String, Proc
533+
msg = exp.pop
534+
end
535+
536+
begin
537+
yield
538+
rescue Test::Unit::PendedError => e
539+
raise e unless exp.include? Test::Unit::PendedError
540+
rescue *exp => e
541+
pass
542+
rescue Exception => e
543+
flunk(message(msg) {"#{mu_pp(exp)} family exception expected, not #{mu_pp(e)}"})
544+
ensure
545+
unless e
546+
exp = exp.first if exp.size == 1
547+
548+
flunk(message(msg) {"#{mu_pp(exp)} family expected but nothing was raised"})
549+
end
550+
end
551+
e
552+
end
553+
517554
TEST_DIR = File.join(__dir__, "test/unit") #:nodoc:
518555

519556
# :call-seq:

tool/test/testunit/test_assertion.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,18 @@ def test_assert_raise_with_message
4747
end
4848
end
4949

50+
def test_assert_raise_kind_of
51+
my_error = Class.new(StandardError)
52+
53+
assert_raise_kind_of(my_error) do
54+
raise my_error
55+
end
56+
57+
assert_raise_kind_of(StandardError) do
58+
raise my_error
59+
end
60+
end
61+
5062
def test_assert_pattern_list
5163
assert_pattern_list([/foo?/], "foo")
5264
assert_not_pattern_list([/foo?/], "afoo")

0 commit comments

Comments
 (0)