Should !=

I expected ‘should !=’ to act the same as ‘should_not ==’. That turned
out
to be incorrect (by design?):

require ‘spec’
require ‘spec/rails’

describe “using ‘should !=’” do
it “seems to treat != as the same as ==” do
1.should != 1 # passes
1.should != 2 # fails
end
end

On Thu, Oct 9, 2008 at 6:47 PM, Mark W. [email protected] wrote:

I expected ‘should !=’ to act the same as ‘should_not ==’. That turned out
to be incorrect (by design?):

We’d love to do that, but Ruby doesn’t provide us the tools we need.
As far as we know, the only way to do that would be to do string evals
on the files instead of using actual code.

Brief explanation:

Object.instance_methods.sort.grep /=/
=> [“==”, “===”, “=~”, “taguri=”]

Note the absence of “!=”.

Try this in irb:

irb(main):001:0> 5.==(5)
=> true
irb(main):002:0> 5.!=(4)
SyntaxError: compile error
(irb):2: syntax error, unexpected tNEQ
5.!=(4)
^

Essentially, ruby interprets this:

5.should == 5

as this:

5.should.==(5)

but it interprets this:

5.should != 4

as this:

!(5.should.==(4))

And since 5 has no way of knowing that it’s part of a negated
expression, there’s no way for rspec (that I know of) to handle this
as you would expect.

Sorry - we all wish it could be so. I imagine the rubinius extended
version will support it though :wink:

Cheers,
David

“Mark W.” [email protected] writes:

end
Sorry for the short message, but yeah this is known. You can search the
mailing list archives and the tracker for other emails. Basically, Ruby
doesn’t let us do this, because it translates
should != 1
into
!(should == 1)
and since (should == 1) is a passing expectation, the thing passes.

You can get around it by using paresetree or a similar technique but
it’s sloooooooow thus has not become a part of rspec.

Pat

Ahh, one of the cool things about Ruby compared to the C family of
languages
comes back to bite me. :slight_smile:

///ark