Changing rake :default to use RSpec

May 29, 2007

I dug around a little before digging into the Rake RDoc (which is great!), but I didn't find anything on the intertubes about this so I figured I'd post here in case somebody else is looking.

Hijacking the default Rails rake tasks is actually pretty easy, but if you just try to redefine it by adding a new task :default it will add to the existing tasks. This is by design, so you can add to existing tasks. So, if you just redefine it and add :spec it will kind of work, but it'll run your tests first.

To solve this all you have to do is clear the existing prerequisite (which runs :test). Put this in a file called default.rake in the lib/tasks directory of your rails project

Rake::Task[:default].prerequisites.clear

That's it! it'll now run your specs instead of tests. Taking it a little bit further, you can use the following as a default.rake instead:

rspec_base = File.expand_path("#{RAILS_ROOT}/vendor/plugins/rspec/lib")
$LOAD_PATH.unshift(rspec_base) if File.exist?(rspec_base)
require 'spec/rake/spectask'
Rake::Task[:default].prerequisites.clear
desc "Run specs with rcov output"
Spec::Rake::SpecTask.new(:default) do |t|
  t.spec_opts = ['--options', "#{RAILS_ROOT}/spec/spec.opts"]
  t.spec_files = FileList['spec/**/*_spec.rb']
  t.rcov = true
  t.rcov_opts = ['--exclude', 'spec,/usr/lib/ruby', '--rails', '--text-report']
end
This will do the same thing, but at the end it will give you a nice RCov spec coverage report. The catch with this is that RSpec will now run twice as - to fix that, you have to open up plugins/rspec_on_rails/tasks/rspec.rake and comment out line #14 ( #task :default => :spec ) This is because Rails loads plugins after it loads lib, so the tasks in rspec_on_rails overide your custom tasks.

Comments

Thanks a lot, that approach worked a lot better and solved my problems.

Add comment

Blog Archives

Recent Comments