运行规范时禁止 Ruby 警告 [英] Suppress Ruby warnings when running specs

查看:71
本文介绍了运行规范时禁止 Ruby 警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在运行规范时抑制 Ruby 警告的方法.

I'm looking for a way to suppress Ruby warnings when I run my specs.

spec spec/models/account_spec.rb

我收到如下警告:

DEPRECATION WARNING: ActiveSupport::Dependencies.load_paths is deprecated, ...
warning: already initialized constant SOME_CONSTANT_NAME

使用 ActiveSupport::Deprecation.silenced = true 可以轻松删除 ActiveSupport 警告.

Removing the ActiveSupport warning is quite easy with ActiveSupport::Deprecation.silenced = true.

作为我的 spec 命令的一部分,我如何防止已经初始化的常量警告?或者通过创建另一个可以抑制此类警告的 spec 文件.请记住,这些警告来自 gem 文件,因此我无法进入这些文件并用 Kernel.silence_warnings 包围它们.

How do I prevent the already initialized constant warnings as part of my spec command? Or through creating another spec file that can suppress such warnings. Keep in mind that these warnings are from gem files, therefore I cannot go into those files and surround them with Kernel.silence_warnings.

注意:我知道抑制警告是不好的.但是,当我从 vim 中运行单个 spec 时,如果警告不会使我的屏幕混乱,那就太好了.

Note: I understand that suppressing warnings are bad. However, when I run a single spec from within vim it would be nice if the warnings didn't clutter my screen.

推荐答案

如果您直接使用 ruby​​ 命令而不是规范包装器运行规范,则可以使用 -W 命令行选项来消除警告:

If you run your specs directly with the ruby command instead of the spec wrapper, you can use the -W command line option to silence warnings:

$ ruby --help
[...]
  -W[level]       set warning level; 0=silence, 1=medium, 2=verbose (default)

所以在你的情况下:

$ ruby -W0 -Ispec spec/models/event_spec.rb

不应向您显示任何警告.

should not show you any warnings.

或者,您可以在加载 gem 之前设置 $VERBOSE=nil,即在 environment.rb 的顶部(如果使用 Rails 3,则在 application.rb 中).请注意,这会始终禁用所有警告.

Alternatively, you could set $VERBOSE=nil before your gems are loaded, ie at the top of your environment.rb (or application.rb if you're on Rails 3). Note that this disables all warnings all the time.

或者,由于您使用的是 Rails,如果您使用的是 Bundler,您应该能够在 Bundler.require 块周围使用 Kernel.silence_warnings:

Or, since you are using Rails, you should be able to use Kernel.silence_warnings around the Bundler.require block if you're using Bundler:

Kernel.silence_warnings do
  Bundler.require(:default, Rails.env) if defined?(Bundler)
end

更有选择性地,设置 $VERBOSE 仅用于加载特定的 gems:

More selectively, set $VERBOSE only for loading specific gems:

config.gem 'wellbehaving_gem'
original_verbosity = $VERBOSE
$VERBOSE = nil
config.gem 'noisy_gem_a'
$VERBOSE = original_verbosity

这篇关于运行规范时禁止 Ruby 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆