Search code examples
ruby-on-railsruby-on-rails-3unit-testingrake-taskrake-test

How do you write a task to run tests in Rails 3?


I would like to write rake tasks to customize tests. For example, to run unit tests, I created a file with the following code and saved it as lib/tasks/test.rake:

task :do_unit_tests do
  cd #{Rails.root} 
  rake test:units
end

Running rake do_unit_tests throws an error: can't convert Hash into String.

Working in Rails 3.0.7 and using built-in unit test framework.

Thanks.


Solution

  • There is no need to cd. You can simply...

    task :do_unit_tests do
      Rake::Task['test:units'].invoke
    end
    

    But if you really want to cd, that's how you call shell instructions:

    task :do_unit_tests do
      sh "cd #{Rails.root}"
      Rake::Task['test:units'].invoke
    end
    

    Well, in fact there is a shorter version. The cd instruction have a special alias as Chris mentioned in the other answer, so you can just...

    task :do_unit_tests do
      cd Rails.root
      Rake::Task['test:units'].invoke
    end
    

    If you want to go further, I recommend Jason Seifer's Rake Tutorial and Martin Fowler's Using the Rake Build Language articles. Both are great.