Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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.

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top