Chris Bunch
Chris Bunch

Reputation: 89873

See if an Exception's message matches a known String in Ruby via Test::Unit

Suppose I have a method written in Ruby that I am unit testing via Test::Unit. This method can raise a SystemExit for more than one reason, but uniquely identifies the reason it throws it in the Exception. I know I can do this to assert that an exception is raised:

assert_raises(SystemExit) { boo() }

But this matches all cases where boo() throws a SystemExit. How could I differentiate cases where boo() did abort("reason 1") from abort("reason 2")?

Upvotes: 2

Views: 360

Answers (2)

Jamie Cook
Jamie Cook

Reputation: 4525

The assert_raises helper already returns you the exception that it catches

e = assert_raises(SystemExit) { boo() }
assert_equal("Reason 1", e.message)

No need to begin/rescue it yourself.

Upvotes: 2

d11wtq
d11wtq

Reputation: 35318

Just trap it with begin..rescue. Write a helper method if you need to do it repeatedly.

begin
  boo()
rescue SystemExit => e
  assert_equal(e.message, "This message")
end

Upvotes: 3

Related Questions