如何使用rake检测故障单元测试

时间:2012-10-17 21:00:38

标签: ruby-on-rails-3 rake

我正在使用Ruby 1.9.3和Rails 3.2.8。这使用rake 0.9.2.2。

我希望检测到失败的单元测试,在Rails 2.3中,我们通过检查退出代码来完成此操作。这不再有效。

我试试:

rake test:units TEST=test/unit/failing_test.rb RAILS_ENV=test && echo "OK"

failing_test.rb由一个断言为false的测试组成。我希望看到测试失败而不是看到“OK”,但相反,我看到了:

Started
F
===============================================================================
Failure: <false> is not true.
test: failing test case should fail. (FailingTest)
test/unit/failing_test.rb:6:in `block (2 levels) in <class:FailingTest>'
shoulda-context (1.0.0) lib/shoulda/context/context.rb:398:in `call'
shoulda-context (1.0.0) lib/shoulda/context/context.rb:398:in `block in create_test_from_should_hash'
activesupport (3.2.8) lib/active_support/testing/setup_and_teardown.rb:72:in `block in run'
activesupport (3.2.8) lib/active_support/callbacks.rb:425:in `_run__3774233495015181374__setup__985181848351195933__callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.8) lib/active_support/callbacks.rb:385:in `_run_setup_callbacks'
activesupport (3.2.8) lib/active_support/callbacks.rb:81:in `run_callbacks'
activesupport (3.2.8) lib/active_support/testing/setup_and_teardown.rb:70:in `run'
===============================================================================


Finished in 0.002753 seconds.

1 tests, 1 assertions, 1 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
0% passed

363.24 tests/s, 363.24 assertions/s
rake aborted!
Command failed with status (1): [/Users/chris/.rvm/rubies/ruby-1.9.3-p194/b...]

Tasks: TOP => test:units
(See full trace by running task with --trace)
OK

具体来说,我看到“命令失败并显示状态(1)”,但这似乎被rake吃掉了,因为我也看到了“OK”。请注意,如果我echo $?,我看到退出代码为0(成功)。我试图在我们的持续集成和我们的发布脚本的上下文中使用它,两者都假设在出现错误时退出代码将不为零,就像Rails 2.3中发生的那样。

1 个答案:

答案 0 :(得分:3)

我使用相同的rails / ruby​​ / rake进行的失败测试正在退出1,与您的不同。也许你的代码库中某处有at_exit { exit 0 }trap('EXIT') { exit 0 }。这将修改rake的退出代码。

如果您想要以非Ruby方式检测故障,可以尝试使用grep读取测试的输出。 grep如果找到匹配则返回0,否则返回1。

正则表达式查找" 0 failures, 0 errors",如果找到则返回0,否则返回1

rake test:units TEST=test/unit/failing_test.rb RAILS_ENV=test | \
  tee >(xargs -0 echo {}) | \ 
  grep '\([[:space:]]0[[:space:]]\)failures,\1errors' && 
  echo OK