
ALERT: There is a way better, newer article on this same topic: http://www.misuse.org/science/2009/03/25/continuous-testing-and-testing-single-methods-in-ruby-on-rails/
I am often running into a problem where I want to test a single function in Ruby on Rails. This used to amount to me building a command line custom statement that would test that file. Today I built a little Rake command that solves this problem once and for all.
Paste the code below into ./lib/tasks/AppTasks.rake file. From the command prompt run:
rake my_app:test file=application_controller
Obviously change “application_controller” to whatever you want to test. You don’t need to specify the name of the testing file (which ends in “_test.rb”), the rake task figures that out for you.
This task will also allow you to run multiple tests on a specific word – let’s say you want to run all test files that have the word “user” in it. Simply write:
rake my_app:test file=user
I hope this code is useful for other people as well. Feel free to use it for any purpose:
# this code should be put in a separate root namespace to all other regular rake tasks..
namespace :my_app do
desc "Run a single test without preparing database first. Smart about finding the test file.nSyntax: rake app:test file=[basename] where basename matches a portion of a test (or multiple tests)."
Rake::TestTask.new(:test) do |t|
if ARGV[1]
# take the first parameter and grab everything right of '=' sign, ignore _test.rb if it exists in parameter
file_pattern = ARGV[1].match(%r{=(.*)})[1]
file_pattern.gsub!(%r{_test.rb|_test}, "")
filelist = FileList["test/**/*#{file_pattern}*_test.rb"]
puts filelist.inspect
t.libs << "test"
t.verbose = true
t.test_files = filelist
end
end
end