Thursday, June 11, 2009

Run focused tests in TextMate with test/unit

If you are using TextMate version 1.5.8 (1498) and want to run focused test (⌘-shift-r) with the test/unit notation

class SimpleTest < Test::Unit::TestCase
test "simple me" do
# test code
end
end

then modify the file

/Applications/TextMate.app/Contents/SharedSupport/Bundles/Ruby.tmbundle/Support/RubyMate/run_script.rb

and add lines 1, 5-7 and 15-16

    1   spec, context, name, test_name = nil, nil, nil
2
3 File.open(ENV['TM_FILEPATH']) do |f|
4 # test/unit
5 lines = f.read.split("\n")[0...n].reverse
6 name = lines.find { |line| line =~ /^\s*def test[_a-z0-9]*[\?!]?/i }.to_s.sub(/^\s*def (.*?)\s*$/) { $1 }
7 # ActiveSupport::Testing::Declarative#test
8 # to use the new test "" do;end syntax
9 test_name = $3 || $4 if lines.find { |line| line =~ /^\s*(test)\s+('(.*)'|"(.*)")+\s*(\{|do)/ }
10 # test/spec.
11 spec = $3 || $4 if lines.find { |line| line =~ /^\s*(specify|it)\s+('(.*)'|"(.*)")+\s*(\{|do)/ }
12 context = $3 || $4 if lines.find { |line| line =~ /^\s*(context|describe)\s+('(.*)'|"(.*)")+\s*(\{|do)/ }
13 end
14
15 if name and !name.empty?
16 args << "--name=#{name}"
17 elsif test_name and !test_name.empty?
18 args << "--name=test_#{test_name.gsub(/\s+/,'_')}"
19 elsif spec and !spec.empty? and context and !context.empty?
20 args << %Q{--name="/test_spec \\{.*#{context}\\} \\d{3} \\[#{spec}\\]/"}
21 else
22 puts "Error: This doesn't appear to be a TestCase or spec."
23 exit
24 end
25