Test Driven Development is something I have heard a lot about in the last year or two but I hadn’t had an opportunity to try it for myself until I started the LevelUp program that ThoughtWorks runs to help students who are close to graduating build skills that they will need as they venture into the workplace.
So what is TDD about? It’s a different programming paradigm to the one I’m used to and the one I’ve been taught at uni. TDD is about writing your tests first, running them to see that they are failing, and then writing the code to ensure the tests will pass. It is about deliberately and incrementally adding small pieces of functionality, all the while making sure that it is comprehensively tested as it is written rather than as an afterthought.
Why bother with Test Driven Development? At first it might seem counterintuitive to write your tests first but as you start to work in a test-driven way, you will notice that your focus changes. Beginning by writing a test provides you with a singular focus – to get the test to pass. It provides you with clear goals for your code to achieve and encourages you to segment functionality in a logical way. In that sense TDD goes hand-in-hand with the well known Object-Oriented principle of single responsibility, where each class and method should have responsibility for a single piece of functionality.
The TDD cycle of ‘write the test – see the test fail – make the test pass’ also provides development teams with an opportunity to refactor code during the cycle. Refactoring is not limited to functional code, but test code can also be rewritten to make it more readable and eliminate unnecessary duplication. A code base that has been consistently refactored will be more readable and more easily extended to support additional functionality in the future.
How can you get started with TDD? In LevelUp we are using RSpec, a TDD framework for Ruby. If you’d like to give it a go check out this Tuts+ article by Andrew Burgess called ‘Ruby for Newbies: Testing with RSpec‘. For those who want a more in-depth look at RSpec, Tuts+ also offer a more comprehensive course in ‘Testing Ruby with RSpec‘ (note: this course is part of the Tuts+ paid subscription service).
Because I’ve been playing around with Python lately, I went on the hunt for TDD Python materials and came across the incredibly useful and comprehensive ‘Beginning Test-Drive Development in Python‘ by David Sale. In addition to taking you through the fundamental concepts of TDD, this tutorial gives step by step instructions for getting started with TDD in Python.