当Rails测试错误时抑制堆栈跟踪

时间:2011-02-03 20:22:38

标签: unit-testing ruby-on-rails-3 stack-trace

我是Ruby on Rails的新手和写作测试。其中一些产生例外;我想“rake test”输出给我异常错误消息但不是整个回溯。 (我想写一些测试来执行未实现的功能,然后我会填写。)

例如,实际输出:

Started
E
Finished in 0.081054 seconds.

  1) Error:
test_should_fail(VersioningTest):
ActiveRecord::StatementInvalid: PGError: ERROR:  null value in column "client_ip" violates not-null constraint
: INSERT INTO "revisions" ("created_at", "id") VALUES ('2011-02-03 20:14:17', 980190962)
    /Users/rpriedhorsky/.rvm/gems/ruby-1.9.2-p136/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract_adapter.rb:202:in `rescue in log'
    /Users/rpriedhorsky/.rvm/gems/ruby-1.9.2-p136/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract_adapter.rb:194:in `log'
    /Users/rpriedhorsky/.rvm/gems/ruby-1.9.2-p136/gems/activerecord-3.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:496:in `execute'
    [... etc. etc. etc. ...]

1 tests, 0 assertions, 0 failures, 1 errors, 0 skips

期望的输出:

Started
E
Finished in 0.081054 seconds.

  1) Error:
test_should_fail(VersioningTest):
ActiveRecord::StatementInvalid: PGError: ERROR:  null value in column "client_ip" violates not-null constraint

1 tests, 0 assertions, 0 failures, 1 errors, 0 skips

我在相反的方向上找到了信息(e.g.),但没有找到抑制堆栈跟踪的信息。

修改

很容易将它们打开和关闭;如下所述,有时它们对于追踪错误很有用。

1 个答案:

答案 0 :(得分:1)

你可以看看“回溯消音器” - 对我来说(Rails 2.3.8),这是文件config / initializers / backtrace_silencers.rb:

# Be sure to restart your server when you modify this file.

# You can add backtrace silencers for libraries that you're using but
# don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }

# You can also remove all the silencers if you're trying do debug a
# problem that might steem from framework code.
# Rails.backtrace_cleaner.remove_silencers!

Rails.backtrace_cleaner.add_silencer {|line| line =~ /gems/}
Rails.backtrace_cleaner.add_silencer {|line| line =~ /passenger/}

看起来你应该能够设置像

这样的行
Rails.backtrace_cleaner.add_silencer {|line| true}

在你的config / environments / test.rb文件中,这会擦掉你的回溯(虽然它可能只适用于记录器 - 我对这个方法不太熟悉)。

但问问自己 - 你真的想完全取消回溯吗?它们对于追踪错误非常有用......