Adding custom before and after actions to Rake tasks

While doing some work for a client recently, I had the need to add some custom database setup to the test process for their rails application. We wanted to put this ┬áprocedure in a rake task, but still wanted to be able to just use the standard rake tasks to run the test, e.g. ‘rake test:units’.

It turns out, that it is very easy to plug custom before and after actions into existing rake tasks. If you want to add a prerequisite to a rake task, use the following code:

Rake::Task[:existing_task].enhance [:prereq1, :prereq2]

Adding custom tasks to be executed after the existing task uses a slightly less obvious syntax with a code block. In my case, I needed an action to run after db:test:prepare, so my code looked something like:

Rake::Task['db:test:prepare'].enhance do

Because its name contains colons, the db:test:prepare task is named with a String instead of a symbol since that is the cleanest syntax available.

Leave a Reply

Your email address will not be published. Required fields are marked *