Learn how to test your code

Published 23 February 10 by Justin French

Recently, I was asked by someone new to Ruby and Rails what advice I had for them. Other than “watch all the Railscasts”, I really only have one piece of advice:

Learn how to test your software through automation.

Learning how to write good tests for my code was the single most important step I made as a developer. I can’t more strongly emphasise this.

You’ll wrestle with it at first. You’ll be perplexed by the choices in testing frameworks and distracted by the subtle differences in terminology. You’ll be frustrated that you’re writing “twice as much code” for every feature. You’ll think you can hold the whole thing in your head and catch yourself making mistakes. Your boss will complain that things are taking too long.

Push through this shit. Sometimes the pay-off isn’t obvious for weeks or even months, but it’s always there.

Your tests are your safety net. You’ll learn to lean on them, to trust them more than you trust yourself. You’ll find you’re no longer terrified by huge changes to the code base, or sudden changes in direction. You’ll see the occasional false alarm too (an “annoying” test that fails, but only exposed a bug in your testing approach).

Eventually (it’s only a matter of time), you’ll change something trivial and confidently commit to your version control system without running your tests. A few minutes later your co-workers (or even better, a continuous integration build server) will catch your mistake with a failing test. Your trivial change just busted another part of the code you weren’t thinking about.

That code you just busted will be hidden somewhere in an obscure path through your shopping cart, and your test suite has just saved your company time, money and a loss of consumer confidence.

The light bulb goes on. You get it, your boss probably gets it, but this is only the start of the journey.

Eventually you’ll forget that you used to spend hours testing your code in a browser, and start complaining that your automated tests are taking minutes to run! You’ll have intense debates with co-workers about what to test and how to test it properly. You’ll start writing the test first to expose the bug or missing feature, then write the code required to pass the test.

This is the moment you realise you care more about your tests than you do about the code.

Options

Search