The Opinionated Programmer #1

On testing rake tasks

Warning: The following post is my personal opinion. If you feel I’m wrong or you disagree with me, please reply to this post and I’ll will be so glad to read your opinions.

Imagine with me for a second. One shiny morning, while working on your amazing project, written in ruby on rails, you needed to automate a job. Well, a job that you want to run may be one time every now and then. Your first choice is writing a rake task, right?

Fast forward .. 30 minutes later, you have your awesome rake task written and staring at you. You run it once. And it works — Yay!

But the TDD daemon inside your brain is still unhappy. It’s rolling in your head “You need to write some tests”. You think “hmm, why not.”

So, you start with a simple test, then another, then a third one, until your discover your tests got more complicated tests plugged into your rake task. But that’s fine, since you feel anyway guilty not doing so, and give some peace to your TDD daemon who makes you think you’re committing a crime not doing so.

I understand. Nothing is wrong with that. But it’s more like buying a helicopter so you can travel two blocks down to your neighbor’s BBQ party. So, I take that back. Yes there’s something wrong with what you’re doing.

I’ll explain:

1- Rake tasks are not meant to be a complicated part of your website. Instead, rake tasks are meant to be “thin” and only to invoke other modules in your system. Those modules do the heavy work. Those modules are what really matters. So, test the meaningful code and not the code that invokes it.

2- You might say “Well, what if I still feel unconfident about those invoking processes?”
Trust rails and trust the whole framework. Don’t bother testing whether this rake task is going to print something minor. It will work. Otherwise, you have a bigger issue that missing tests in the framework.

3- If you’re spending time writing super complicated tests for every rake task you have, you are then repeating yourself, which is a waste of your time. Again, your rake tasks are meant to invoke some other code that should be tested separately. And because rake tasks are mostly a method of delivery, or a vehicle to this functionality, your tests, if needed, should be very short and simple.

In summary: Focus your energy more on testing the functionality that this rake task is written to invoke, which is a class or a method some where else in your models or lib files or any where else.

Happy coding!