Conveniently run one spec file from Rake

After my frustrating ordeal with Autotest last night, I decided that if Autotest didn't want to cooperate, I at least needed to set up an easier way to manually run specs for a single file.

This rule allows more convenient access to individual spec files, without the hassle of rake spec SPEC_FILE="spec/foo_spec.rb".

require 'spec/rake/spectask'

rule(/spec:.+/) do |t|
  name ="spec:","")

  path = File.join( File.dirname(__FILE__),'spec','%s_spec.rb'%name )

  if File.exist? path do |t|
      t.spec_files = [path]

    puts "\nRunning spec/%s_spec.rb"%[name]

    puts "File does not exist: %s"%path


It dynamically creates and invokes a SpecTask depending on the task name you give it. For example, if you run rake spec:color, it will run the specs in spec/color_spec.rb. You can run multiple specs (rake spec:color spec:music spec:surface), or even run specs in a subdirectory of spec (rake spec:foo/bar).

For completeness, I also defined a spec:all task which runs all specs. This is pretty simple, but I'll post it here in case it helps someone:

namespace :spec do
  desc "Run all specs" do |t|
    t.spec_files = FileList['spec/*_spec.rb']


Shawn Anderson submitted a comment on #

looks like you have a typo on this line:

path = File.join( File.dirname(__FILE__),'spec','%s_spec.rb'%name )

the ‘spec’ should be ‘specs’, right?

John Croisant submitted a comment on #

It depends on what the folder is called. In this case I’m assuming they’re in “spec/”, so the line is correct. If your specs are in another directory, you’d want to change that line, of course.

Have something interesting to add to the discussion? Email your thoughtful comments to