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.
rspec-expectations is the gem that adds
should
to every object. Requiringrspec
loads only the rspec meta gem (which exists purely to be a singlegem 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 firstdescribe
call, for historical reasons, as explained in my blog post.So, if you want to make
Object#should
immediately available, you simply need to requirerspec/expectations
. Note that we plan to change the default in RSpec 4 so thatshould
is not automatically available without extra config. Also, as @JonRowe mentioned, this usage isn't really the intended usage. You can callfoo.should
from any context, but the matcher methods that are meant to work withshould
are not available in all contexts. You'll need to includeRSpec::Matchers
into your context to make them available. Consider also switching to theexpect
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 adescribe
block. Please don't use it in this fashion.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 byenable by default
means within an spec file [source] only. For instance: