An introduction to TDD
Today Cedric and I had a session about TDD.
What’s that?
TDD, or Test Driven Development, is the very-handy practise of testing your code as it is written. A test is written (no code yet!) and should fail. Once it fails some code can be written to make the test pass. Once the test passes it can be refactored if need be. After these three steps produce a passing test, the next test can be written, and the process repeated.
This may seem like a time-consuming exercise, but it is outrageously valuable for things like:
- helping you to figure out what you want to the code to do, therefore creating detail in your specifications.
- keeping your code DRY and concise. This is because it forces you to write code only in response to the tests.
- reducing time spent reworking the code. If details must be changed it is easy to ensure they don’t break other specs.
- also reducing time spent debugging if you can see exactly where the problem resides.
- being advantageous in the development of the code’s intention and your changing understanding of the nature of the problem.
In the words of Uncle Bob, the three rules of Test Driven Development are:
- You are not allowed to write any production code unless it is to make a failing unit test pass.
- You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
- You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
This method is also known as red, green, refactor. A test is red (fails) until a test is green (passes) and then it can be refactored.
Applying TDD
In Ruby the gem used for TDD is Rspec. You can install this on your terminal and get straight to writing tests and running Rspec. This tutorial from Tuts+ will give you an understanding of how to set up rspec and file structure, as well as how the tests run. So how might I apply TDD with Rspec to a kata?
Cedric and gave this problem:
Find all the numbers under a limit of n that are divisible by 3 or 5, and then return the sum of these numbers.
He wanted me to think through the problem before I solved it, and I wrote out my scramble thoughts in bad pseudo code:
Not an incredibly clear structure here, but the idea was to figure out the problem in my head first, before I attempted to solve it. To know the problem is to know what tests to write and what their outcomes should be.
This is how it might start:
Another Resource…
There is a secret, for-spies-only, resource in the comments section of this blog-post (still valid?) if you want a more involved tutorial of Test Driven Development. Plus the tutor has an excellent moustache!
P.s. This is not the moustachioed tutor, this is you being a spy, and also owning a very good crumb-catcher.