2

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.

B Seven
  • 44,484
  • 66
  • 240
  • 385

2 Answers2

3

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.

Community
  • 1
  • 1
jmonteiro
  • 1,702
  • 15
  • 25
  • 1
    I suppose you may highlight the sentence: "There is no need to cd". I would say it may also be a little dangerous when not called with a block, because it would (if it wasn't already the same) change the current directory for all other actions. And also your first suggestion of using `sh "cd ..."` would not work, because the path would be changed only in a new process of shell, which ends as soon as the directory is changed. – Arsen7 Sep 12 '11 at 15:54
1

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
Chris
  • 9,994
  • 3
  • 29
  • 31
  • This throws an error: `undefined local variable or method 'units' for main:Object`. – B Seven Sep 11 '11 at 06:07
  • I only read and fixed the first line. I've now updated the second line to be a system command, so there's no errors in the code. Still, there's more appropriate ways to do this, as [jmonteiro](http://stackoverflow.com/users/131947/jmonteiro) has described. – Chris Sep 11 '11 at 07:24
  • This threw an error as well. Adding `--trace` reveals `rake aborted!Command failed with status (1): [/home/baller/.rvm/rubies/ruby-1.9.2-p180/b...] /home/baller/.rvm/gems/ruby-1.9.2-p180/gems/rake-0.8.7/lib/rake.rb:995:in 'block in sh'` – B Seven Sep 11 '11 at 14:33