Add your Rails 3 lib tests to rake:test

I have a large Rails 3 project with lots of reusable code in modules. Tests for these modules are placed in test/lib to isolate them from database-heavy model tests. In order to run these tests automatically along with my unit, functional, and integration tests, I implemented the solution described here some time ago. However, at some point over the last year, either Rake or Rails or both broke this (I'm leaning towards Rails, since the new tasks in the Railties gem look much more complex, with special subtasks derived from the Rake::TestTask class). I've been looking for a new approach, and today I got fed up and started fixing it myself.

If you want to run Test::Unit tests in test/lib, try putting the following in lib/tasks/test_lib.rake:

require 'rubygems'
require 'rake'

namespace :test do
  desc "Test lib modules"
  Rake::TestTask.new(:lib) do |t|    
    t.libs << "test"
    t.pattern = 'test/lib/**/*_test.rb'
    t.verbose = true    
  end
end

class Rake::Task
  def overwrite(&block)
    @actions.clear
    enhance(&block)
  end
end

Rake::Task["test:run"].overwrite do
  errors = %w(test:units test:functionals test:integration test:lib).collect do |task|
    begin
      Rake::Task[task].invoke
      nil
    rescue => e
      { :task => task, :exception => e }
    end
  end.compact

  if errors.any?
    puts errors.map { |e| "Errors running #{e[:task]}! #{e[:exception].inspect}" }.join("\n")
    abort
  end
end

For more information on how the test tasks work, examine the source.

Written on Wednesday, June 27, 2012 | Tags: rails, rake, testing