2011-06-29 45 views
26

而不是自动运行所有的测试用例,有没有办法在ruby测试/单元框架下执行单个测试。我知道我可以通过使用Rake来实现这一目标,但我现在还没有准备好转换为Rake。如何使用Ruby测试/单元执行单个测试?

ruby unit_test.rb #this will run all the test case 
ruby unit_test.rb test1 #this will only run test1 

回答

39

你可以通过-n选项在命令行中运行一个测试:

ruby my_test.rb -n test_my_method 

其中“test_my_method”是你想运行测试方法的名称。

+1

+1正是我想要的。但是我只在6分钟后才接受它.. – pierrotlefou

+3

如果你喜欢长选项,完整的选项是'--name'。 –

+3

还支持正则表达式:ruby my_test.rb -n /test_.*/ – imwilsonxu

8

如果您寻找非shell解决方案,您可以定义一个TestSuite。

实施例:

gem 'test-unit' 
require 'test/unit' 
require 'test/unit/ui/console/testrunner' 

#~ require './demo' #Load the TestCases 
# >>>>>>>>>>This is your test file demo.rb 
class MyTest < Test::Unit::TestCase 
    def test_1() 
    assert_equal(2, 1+1) 
    assert_equal(2, 4/2) 

    assert_equal(1, 3/2) 
    assert_equal(1.5, 3/2.0) 
    end 
end 
# >>>>>>>>>>End of your test file 


#create a new empty TestSuite, giving it a name 
my_tests = Test::Unit::TestSuite.new("My Special Tests") 
my_tests << MyTest.new('test_1')#calls MyTest#test_1 

#run the suite 
Test::Unit::UI::Console::TestRunner.run(my_tests) 

在现实生活中,测试类MyTest的将从原始测试文件中加载。