24 July 2016

A Hole in the Net

  I happen to think unit testing is the bees knees and is absolutely required in the creation of readable, maintainable working code. However, things can go wrong. Here is something that bit me in the arse not too long ago.

  The code itself was trying to create a hash with a key for every hour in a 24hr clock (the project I was using this for is here if you'd like to know the context). This means I needed a key from 0 up to 23. I know a number of ways of doing this in Ruby, but I settled on using the `times` method. My first mistake was I used the wrong number of times in my unit test. My second and frankly worse mistake, I used this method in my unit test but then used the same code in my implementation. So my unit test was happily passing because my production code was written to it, but it wasn't actually doing what I had intended.

  Fortunately, as I hope we are all aware, unit testing is but one of the many nets we use to catch bugs. I found this one with my exploratory testing net.

P.s. Keen-eyed readers will notice that the unit test code and the implementation code in the project are still the same and will be wondering if I've truly learnt anything from this experience. The reason is, the destination may be the same, but the route was different. Having used a different method to confirm the implementation was correct, I refactored the unit test to be more readable for me.

No comments:

Post a Comment