Home
subscribe

L'etat, c'est moi

Mere Complexities sells the consulting and development services of me, Paul Wilson.

Conferences

Organising Scotland on Rails
Speaker, RailsConf Europe '08

Archive

Smart Tests Are Dumb Tests

Johnny Bravo

A question I hear a lot is “don’t you find your test code is pretty much a copy of your production code?” Digging deeper we this kind of test.


def test_counts_the_correct_number_of_words
  sentence = 
    "The quick brown fox jumps over the lazy dog."
  expected_count = sentence.scan(/\w+/).size
  analyser = SentenceAnalyser.new(sentence)
  assert_equal expected_count, analyser.word_count
end

Here’s what I’d write.


def test_counts_the_correct_number_of_words
  assert_equal 9, 
    SentenceAnalyser.new(
        "The quick brown fox jumps over the lazy dog.").word_count
end

The more work we make our tests do, the more likely we are to introduce mistakes in the test code; this can be especially dangerous if we use the same algorithm as in the production code as we can make the same mistake in both places. And that’s apart from the second test being shorter and easier to understand.

So remember, kids, keep your tests dumb to keep them smart.

All