1. In my head, I know what I want a method to do before I even write it, so I write a test that will pass if the code (that I write in step 2) works. In this case it is a basic method in one of my Models.
2. To make the test pass, here is my REAL method that I add to my model….
3. Now lets run the test…
4. Some other guy on the team changes some code…
5. Looking at the change, it won’t work. The passed arg IS an array, so it will throw an exception. But my original test will catch the fact that this method does not work anymore, otherwise this bug could have gone unnoticed.
From the failed test, you can even see which line of code is failing.
Obviously if you have not written a test for something it can not fail, so being thorough and making sure any bit of functionality has been tested its easy to catch problems and fix bugs.
And if you’re using Git, you can even see who broke the project. Then take it in turns to beat the developer around the head with a blunt instrument.
The worlds most basic summary
Ask yourself “The code I am about to write, what should it do/not do” – then write a test that covers any conceivable eventualities FIRST. Then write the real code to make the test pass.