【问题标题】:rspec's .should fails (outside describe/it block) in Ruby 2?rspec 的 .should 在 Ruby 2 中失败(在 describe/it 块之外)?
【发布时间】:2014-02-17 21:35:02
【问题描述】:

在 Ruby 2 中,使用 gem rspec 2.14.1(Ubuntu 的最新版本),未安装 Rails,为什么会失败?

require 'rubygems'
require 'rspec'
3 .should == 3

NoMethodError: undefined method `should' for 3:Fixnum

多年来,我一直依赖方便的成语x .should == y

https://www.relishapp.com/rspec/rspec-expectations/v/2-14/docs/syntax-configurationhttps://www.relishapp.com/rspec/rspec-expectations/docs/syntax-configuration 表示默认仍支持此语法。

编辑:在标题中添加了“outside describe/it block”,因为这似乎是根本原因。

【问题讨论】:

  • 我怀疑你可以在describe/it 块之外使用它

标签: ruby rspec ruby-2.0


【解决方案1】:

如果您想在 describe/it 块之外使用它,似乎您必须先启用它,尽管文档声明它默认启用。我假设 enable by default 仅表示在规范文件 [source] 中。例如:

require 'rubygems'
require 'rspec'

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :should
  end
end

p 3.should == 3 # true

【讨论】:

  • 这是正确的。补充,也更喜欢expect 而不是should 推荐的betterspec
【解决方案2】:

rspec-expectations 是将should 添加到每个对象的gem。要求 rspec 仅加载 rspec 元 gem(它的存在纯粹是作为提供所有 rspec 的单个 gem install),但不会自动加载 rspec-expectations。如果您愿意,rspec-core 允许您将其配置为使用除 rspec-expectations 之外的其他内容(例如 minitest 提供的 stdlib 断言或错误),但它默认加载 rspec-expectations。为了实现这一点,如果你没有显式配置它,它会等待加载 rspec-expectations 直到第一个 describe 调用,由于历史原因,explained in my blog post

因此,如果您想让Object#should 立即可用,您只需要求rspec/expectations。请注意,我们计划更改 RSpec 4 中的默认值,以便 should 在没有额外配置的情况下不会自动可用。此外,正如@JonRowe 提到的,这种用法并不是真正的预期用法。您可以在任何上下文中调用foo.should,但用于should 的匹配器方法并非在所有上下文中都可用。您需要将RSpec::Matchers 包含在您的上下文中以使其可用。还可以考虑切换到expect 语法:它是一种更新的、非猴子补丁的语法,我们一直使用recommending for a while now

【讨论】:

  • 我一直在使用 .should,就像 C 的 assert()。 (就在昨天,我在 SO 上取笑其他人使用 C 习语而不是 Ruby 习语!)我将学习 expect
  • 感谢 Myron 的详尽撰写。
【解决方案3】:

它在 RSpec 示例之外不受支持,例如在 it 块内 describe 块内。请不要以这种方式使用它。

【讨论】:

  • 欢迎来到 SO,乔恩。 +1,这样我就可以将您的代表提高一个数量级。 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多