You Don't Need `assert_nothing_raised`

A blog post based on my Testing Anti-Patterns Talk

According to this page assert_nothing_raised is the 9th most commonly used assertion in ruby. Here’s the thing, you don’t need it. Further, you get better debugging information when you don’t use it. Here’s an example:

def raise_something
  raise "WOOT"
end

class Fails < Test::Unit::TestCase

  def test_assert_nothing_raised
    assert_nothing_raised do
      raise_something
    end
  end

end

Here’s the output from this:

# Running tests:
F

  1) Failure:
test_assert_nothing_raised(TestClass) [assert_nothing_raised.rb:9]:
Exception raised:
<#<RuntimeError: WOOT>>.

1 tests, 1 assertions, 1 failures, 0 errors

When you use assert_nothing_raised the error trace points you back at the line with the assertion on it. In this case that’s line

  1. The output doesn’t tell you which line in the block threw the exception and it doesn’t tell you which line in your implementation threw the exception. This means that when you use assert_nothing_raised you know something went wrong but you don’t know what and you don’t know where. It is quite the Schrödinger’s cat of test failures.

Since test_unit and minitest both fail if a test throws an exception you can just leave out the assert_nothing_raised like this:

def raise_something
  raise "WOOT"
end

class Fails < Test::Unit::TestCase

  def test_does_not_raise
                              
    raise_something

  end

end

Without assert_nothing_raised you more details on failure:

# Running tests:
E

  1) Error:
test_does_not_raise(TestClass):
RuntimeError: WOOT
    assert_nothing_raised.rb:4:in `raise_something'
    assert_nothing_raised.rb:15:in `test_does_not_raise'

1 tests, 0 assertions, 0 failures, 1 errors

In this case you know exactly where in the code the exception was thrown (both in the test and in the implementation). This makes debugging much easier. Also without assert_nothing_raised you have less overall code. I’d much rather have less code and better output so I don’t use assert_nothing_raised.

If you don’t believe me here are two other people discussing this issue. Assert Nothing Tested PATCH tests: remove assert_nothing_raised (part 2)