[rspec-devel] actual.should != not_expected

Nick Sieger nicksieger at gmail.com
Tue Oct 17 10:03:18 EDT 2006


On 10/17/06, David Chelimsky <dchelimsky at gmail.com> wrote:
>
>
> NOTE that the error reads "4 should == 3". It looks as though ruby is
> actually delivering the == operator instead of !=. Now if you do this:
>
> irb(main):003:0> Object.methods.sort
> => ["<", "<=", "<=>", "==", "===", "=~", ">", ">=",...]
>
> ... you'll note that != is not an actual operator. So I'm not
> convinced that we can get this to work without a big change to rspec's
> internals.


I'm not convinced it's all that useful either.  The only reason I can see
would be the principle of least surprise, and the fact the negative
operators (!=, !~) don't behave as the others do.

I was curious about this behavior, so I dug in a little bit.  Apologies if
this is not new information for some, but I thought it might be worth
sharing.

As you've probably guessed, Ruby treats the != operator as !(a == b).  The
problem for RSpec is that the should helper won't see the ! until after it's
too late.

For evidence, see Ruby's parse.y (line 1184 in 1.8.4):

        | arg tNEQ arg
            {
            $$ = NEW_NOT(call_op($1, tEQ, 1, $3));
            }

and this output from ParseTree:

echo "class A; def meth(actual, value); actual.value.should != value; end;
end" | parse_tree_show
[[:class,
  :A,
  :Object,
  [:defn,
   :meth,
   [:scope,
    [:block,
     [:args, :actual, :value],
     [:not,
      [:call,
       [:call, [:call, [:lvar, :actual], :value], :should],
       :==,
       [:array, [:lvar, :value]]]]]]]]]

So Ruby is evaluating "actual.should != value" as "!(actual.should ==
value)".  Unfortunately, it looks like you can't override the behavior of
the NOT operator (search for NODE_NOT in eval.c), so I don't see an easy way
for this to be implemented without adding further syntax to the RSpec DSL.

Cheers,
/Nick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://rubyforge.org/pipermail/rspec-devel/attachments/20061017/59cba5cf/attachment.html 


More information about the rspec-devel mailing list