Adding to the default Rake task

You have a Rails app with a Rakefile. When you type rake, it runs all the tests (or specs if you prefer). You want it to do something else as well: let’s say you want to run RuboCop on your codebase.

Don’t do this:

task(:default).clear
task default: [:spec, :rubocop]

Do this instead:

task(:default).prerequisites << task(:rubocop)

Update or just this: as Avdi points out, it’s the same.

task default: :rubocop

With the first pattern, you need to collect together all the tasks in one place, and it’s easy to accidentally redefine the prerequisites so that something that you thought was running isn’t any longer.

With the second pattern, however, you can configure each additional task in a self-contained file in lib/tasks/[name].rake, and they won’t step on each other.

Comments

  1. Avdi

    Wrote at 2014-08-30 13:33 UTC using Chrome 36.0.1985.143 on Linux:

    Do you find this behaves differently from adding a dep using ordinary dependency syntax?

    task :default => :rubocop
  2. Paul Battley

    Wrote at 2014-08-30 16:33 UTC using Firefox 30.0 on Linux:

    Oh, good point, Avdi. It’s exactly the same. I think it’s a little bit more obvious that it’s adding a prerequisite rather than (possibly) redefining the task. (It’s not, but I don’t write Rakefiles nearly often enough to be really confident.)

    The thing that puzzles me is: why do I keep seeing the first clear-task-and-redefine idiom all over the place?
  3. Piotr Szotkowski

    Wrote at 2014-09-06 07:14 UTC using Firefox 32.0 on Linux:

    Oh, I wasn’t aware RSpec hooks to the default task even when it’s not explicitly mentioned, thanks! minitest doesn’t, so my Rakefiles sport

    task default: %i(spec rubocop reek)

    (BTW: RuboCop is nice, but trying to make Reek happy is what taught me more OO than anything else in the past year.)