Testing rake tasks

Relying on rake task to do some repetitive work is a really common way in most
rails apps. Testing those tasks seems to not be as common so.

Why?

Personally I think this is mainly due to just not being present in the default
tests stack, so as a developer I assume they are not worth testing because nobody
else is. But actually I think a task which is essential to your application
should be tested never the less, so to ease my journey towards better test
coverage for rake tasks in my own apps I decided to create a little helper to
setup just the basic environment and about as important, be there as a reminder
that I should test those tasks.

Personally I come to like minitest to test rails apps, so the
gist is based on
minitest, but can easily be adapted for any other framework. Looking through the
code you’ll find some conventions I personally like to be enforced in my rake
tasks

  • namespace the task under the app name if it directly interacts with the app
  • put the tasks in sub directories under lib/tasks so it does not become a
    junk drawer of code
  • put each task in its own file
  • name the file after the task (common sense I guess but not always true)

so here we go, enjoy!

https://gist.github.com/sideshowcoder/5891019.js

Running minitest with zeus

Since minitest is supposed to be the new default in Rails 4, and I am really
fund of it I recently switched a pet project of mine over. One problem I ran
into was using zeus to speed up my test flow. So there are a couple of things to
look out for when using zeus with minitest-rails.

Rake and zeus don’t match

In most cases when using minitest people will run their tests via rake. This
actually makes a lot of sense normally since rake offers even a special test
task for it, but with zeus we have a different story here. Since rake will
actually load in the environment when running the tests, you don’t actually get
a lot of benefits when running via zeus, so make sure you run your tests via the
provided test task from zeus, which is base on m.

My tests run twice?

Minitest installs a test runner, at the exit hook of the ruby process, so your
tests will run, and then they run on exit again. This is weird, and should only
happen when autorun is required but somewhere deep in rails this is done, so you
need to make sure it doesn’t happen. There is a nice discussion around this
issue with some proposed fixes here
as well as a pull request by me.

So here you go enjoy minitest and zeus