César D. Velandia

60 seconds to TDD


This quick tutorial presents a minimal setup with Python to start coding using TDD. It only requires two lightweight dependencies nose and when-changed available through pip .

Install and run

sudo pip install nose 
sudo pip install when-changed

The following snippet creates a Makefile and watches for changes in the test folder

mkdir test
touch Makefile
echo -e "tests: \tnosetests dev_test: \twhen-changed -r test 'clear && make tests'; " >> Makefile
#start watching for changes in test/
make dev_test

And write your tests

Next, start writing your tests and put them in the test folder, a first minimal test would look like:

# test/test_minimal.py
from nose.tools import *

def test_read_file():
    assert False

This test will obviously fail but it is a good starting point.

nosetests
.
--------------------------------------------------------------
Ran 1 tests in 0.003s

FAILED (failures=1)

Afterwards, you can start writing your classes, methods, etc. and testing them:

# file_reader.py
def read_file():
    # insert read logic here 
    return number_of_words;

# test/test_minimal.py
from nose.tools import *
from file_reader import *

def test_read_file():
    assert read_file() > 0

A nutshell definition of TDD (by M. Fowler) reads:

To recap, simply follow these three simple steps iteratively:

  • Write a test for the next bit of functionality you want to add.
  • Write the functional code until the test passes.
  • Refactor both new and old code to make it well structured 🔑

As Fowler points out, the key to proper TDD lies on the refactoring step.