Conveniently run one spec file from Rake

(June 19, 2008 @ 01:28 PM)

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".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
require 'spec/rake/spectask'

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

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

  if File.exist? path
    Spec::Rake::SpecTask.new(name) do |t|
      t.spec_files = [path]
    end

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

    Rake::Task[name].invoke
  else
    puts "File does not exist: %s"%path
  end

end

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:

1
2
3
4
5
6
namespace :spec do
  desc "Run all specs"
  Spec::Rake::SpecTask.new(:all) do |t|
    t.spec_files = FileList['spec/*_spec.rb']
  end
end

2 Responses to “Conveniently run one spec file from Rake”

  1. Shawn Anderson Says:

    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?

  2. jacius Says:

    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.

Sorry, comments are closed for this article.