7.0. Introduction

If you cringe at the idea of testing software, then you should to think about the alternatives, and what testing really means. Historically, testing was assigned to the most junior member of the team, a summer intern, or even someone who's not really very good but can't be fired. It's not taken seriously. And testing normally doesn't take place until after the application has been declared "finished" (or some value of finished): it's often an afterthought that delays your release schedule precisely when you can't afford any delays.

But it doesn't have to be this way. Most programmers find debugging much more unpleasant than testing. Debugging is usually what triggers mental images of staring at someone else's code, trying to understand how it works, only so you can fix the part that doesn't actually work. Debugging is almost universally accepted as being an unpleasant task. (If you're thinking that you sometimes get a kick out of debugging, then imagine fixing a bug, only to have it crop up again repeatedly, perhaps with slight variations. The joy of solving the mystery becomes something more like mopping floors.)

The fact that debugging can be unpleasant is exactly what makes testing appealing and, as it turns out, enjoyable. As you build up a suite of tests for each part of your application, it's as if you're buying insurance that you won't have to debug that code in the future. Thinking of tests as insurance helps explain the testing term coverage. Code that has tests written for all the conceivable ways it may be used has excellent coverage. Even as bugs inevitably slip through holes in your coverage, writing tests as you fix these bugs will keep them from recurring.

Writing tests as bugs are discovered is a reactive approach to testing. This is really just debugging with test writing added in; it's good practice, but there's an even better approach. What if you could remove debugging from the process of software development altogether? Eliminating (or minimizing) debugging would make developing software much more pleasant; knowing that your code is solid makes it easier to predict schedules, and to minimize unpleasant last-minute surprises as the release date approaches.

A proactive approach to testing is to write your tests first. When you start an application or new feature, begin by thinking about what that code should and shouldn't do. Think of this as a part of the specification phase, where instead of producing a specification document, you end up with a suite of tests that serve the same purpose. To find out what your application is supposed to do, refer to these tests. Use them to drive the development of your application code, and, of course, use them to make sure your code is working correctly. This is known as test driven development or TDD: a surprisingly productive software development methodology that has excellent support in Rails.