Carina C. Zona bio photo

Carina C. Zona

Email Twitter LinkedIn

Much of Ruby 1.9.x's MiniTest library (the replacement and mimic for the former Unit/Test library) is pretty straightforward. Most commonly the pattern is:
assert_something(expected, actual, optionalMessage)

Sometimes you need to verify that specific conditions will cause the app to raise an exception as it should. This is where MiniTest's syntax diverges a bit from its usual routine. The critical part to make note is: pass actual in a block. The encapsulation allows MiniTest to capture, evaluate, and usefully report on the outcome; rather than summarily halt execution.

Assertion

assert_raises(expectedException) {code block that will actually raise that exception}
assert_raises(NoMethodError) {Integer.fizzbuzz}

Expectation

proc {code block that will actually raise that exception}.must_raise(expectedException)
proc {Integer.fizzbuzz}.must_raise(NoMethodError)

Head's up

Notice a more subtle variation? "must_raise" vs. "assert_raises" <<-trailing "s"

Don't get tripped up.