Search code examples
ruby-on-railsrubytestunit

How to run multiple Rails unit tests at once


I often run the various test groups like:

rake test:units
rake test:functionals

I also like to run individual test files or individual tests:

ruby -Itest test/unit/file_test.rb
ruby -Itest test/unit/file_test.rb -n '/some context Im working on/'

There's also:

rake test TEST=test/unit/file_test.rb

And I've even created custom groupings in my Rakefile:

  Rake::TestTask.new(:ps3) do |t|
    t.libs << 'test'
    t.verbose = true
    t.test_files = FileList["test/unit/**/ps3_*_test.rb", "test/functional/services/ps3/*_test.rb"]
  end

What I haven't figured out yet is how to run multiple ad-hoc tests at the command line. In other words, how can I inject test_files into the rake task. Something like:

rake test TEST=test/unit/file_test.rb,test/functional/files_controller_test.rb

Then I could run a shell function taking arbitrary parameters and run the fast ruby -Itest single test, or a rake task if there's more than one file.


Solution

  • I ended up hacking this into my RakeFile myself like so:

    Rake::TestTask.new(:fast) do |t|
      files = if ENV['TEST_FILES']
        ENV['TEST_FILES'].split(',')
      else
        FileList["test/unit/**/*_test.rb", "test/functional/**/*_test.rb", "test/integration/**/*_test.rb"]
      end
    
      t.libs << 'test'
      t.verbose = true
      t.test_files = files
    end
    Rake::Task['test:fast'].comment = "Runs unit/functional/integration tests (or a list of files in TEST_FILES) in one block"
    

    Then I whipped up this bash function that allows you to call rt with an arbitrary list of test files. If there's just one file it runs it as ruby directly (this saves 8 seconds for my 50k loc app), otherwise it runs the rake task.

    function rt {
      if [ $# -le 1 ] ; then
        ruby -Itest $1
      else
        test_files = ""
        while [ "$1" != "" ]; do
          if [ "$test_files" == "" ]; then
            test_files=$1
          else
            test_files="$test_files,$1"
          fi
          shift
        done
        rake test:fast TEST_FILES=$test_files
      fi
    }