rspec's .should fails (outside describe/it block) in Ruby 2?

瘦欲@ 提交于 2019-12-11 03:54:35

问题


In Ruby 2, with gem rspec 2.14.1 (Ubuntu's most recent), with Rails not installed, why does this fail?

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

NoMethodError: undefined method `should' for 3:Fixnum

I've relied for years on the convenient idiom x .should == y.

https://www.relishapp.com/rspec/rspec-expectations/v/2-14/docs/syntax-configuration and https://www.relishapp.com/rspec/rspec-expectations/docs/syntax-configuration say that this syntax is still supported by default.

Edit: added "outside describe/it block" to title, as that seems to be the root cause.


回答1:


If you want to use it outside a describe/it block, it seems you'd have to enable it first, although the documentation states it is enabled by default. I assume that by enable by default means within an spec file [source] only. For instance:

require 'rubygems'
require 'rspec'

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

p 3.should == 3 # true



回答2:


rspec-expectations is the gem that adds should to every object. Requiring rspec loads only the rspec meta gem (which exists purely to be a single gem install that provides all of rspec), but does not automatically load rspec-expectations. rspec-core allows you to configure it to use something besides rspec-expectations if you wish (such as the stdlib assertions provided by minitest, or wrong), but it loads rspec-expectations by default. To achieve this, if you do not explicitly configure it, it waits to load rspec-expectations until the first describe call, for historical reasons, as explained in my blog post.

So, if you want to make Object#should immediately available, you simply need to require rspec/expectations. Note that we plan to change the default in RSpec 4 so that should is not automatically available without extra config. Also, as @JonRowe mentioned, this usage isn't really the intended usage. You can call foo.should from any context, but the matcher methods that are meant to work with should are not available in all contexts. You'll need to include RSpec::Matchers into your context to make them available. Consider also switching to the expect syntax: it's a newer, non-monkeypatching syntax we've been recommending for a while now.




回答3:


It's not supported outside of an RSpec example, e.g. inside an it block inside a describe block. Please don't use it in this fashion.



来源:https://stackoverflow.com/questions/21839718/rspecs-should-fails-outside-describe-it-block-in-ruby-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!