You Don't Need `assert_nothing_raised`

This is part of the Testing Anti-Patterns series.

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
2
3
4
5
6
7
8
9
# 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 9. 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
2
3
4
5
6
7
8
9
10
# 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)