How do you write a task to run tests in Rails 3?
-
28-10-2019 - |
题
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.
解决方案
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.
其他提示
You're trying to interpolate a value that's not in a string, and you're also treating rake test:units
like it were a method call with arguments, which it's not.
Change the cd
line so you're calling the method with the value of Rails.root
, and change the second line to be a shell instruction.
task :do_unit_tests do
cd Rails.root
`rake test:units`
end