Default task for namespace in Rake

Given something like:

namespace :my_tasks do
  task :foo do
    do_something
  end

  task :bar do
    do_something_else
  end

  task :all => [:foo, :bar]
end

How do I make :all be the default task, so that running rake my_tasks will call it (instead of having to call rake my_tasks:all)?


Place it outside the namespace like this:

namespace :my_tasks do
  task :foo do
    do_something
  end

  task :bar do
    do_something_else
  end

end

task :all => ["my_tasks:foo", "my_tasks:bar"]

Also... if your tasks require arguments then:

namespace :my_tasks do
  task :foo, :arg1, :arg2 do |t, args|
    do_something
  end

  task :bar, :arg1, :arg2  do |t, args|
    do_something_else
  end

end

task :my_tasks, :arg1, :arg2 do |t, args|
  Rake::Task["my_tasks:foo"].invoke( args.arg1, args.arg2 )
  Rake::Task["my_tasks:bar"].invoke( args.arg1, args.arg2 )
end

Notice how in the 2nd example you can call the task the same name as the namespace, ie 'my_tasks'


Not very intuitive, but you can have a namespace and a task that have the same name, and that effectively gives you what you want. For instance

namespace :my_task do
  task :foo do
    do_foo
  end
  task :bar do
    do_bar
  end
end

task :my_task do
  Rake::Task['my_task:foo'].invoke
  Rake::Task['my_task:bar'].invoke
end

Now you can run commands like,

rake my_task:foo

and

rake my_task

I suggest you to use this if you have lots of tasks in the namespace.

task :my_tasks do
  Rake.application.in_namespace(:my_tasks){|namespace| namespace.tasks.each(&:invoke)}
end

And then you can run all tasks in the namespace by:

rake my_tasks

With this, you don't need to worry to change your :all task when you add new tasks into that namespace.


I use this Rakefile for cucumber:

require 'cucumber'
require 'cucumber/rake/task'

namespace :features do
  Cucumber::Rake::Task.new(:fast) do |t|
    t.profile = 'fast'
  end

  Cucumber::Rake::Task.new(:slow) do |t|
    t.profile = 'slow'
  end

  task :ci => [:fast, :slow]
end

task :default => "features:ci"

Then if I type just:

rake

It runs the default task, which runs both fast and slow tests.

I learned this from Cheezy's blog.