Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid the "Useless use of == in void context" in RSpec?

In RSpec, if I have warnings on and have

x.should == 42
another_line_of_code

then I get a warning about

warning: useless use of == in void context

Is there anything I can do other than

  1. Turn warnings off
  2. Change it to bitbucket = (x.should == 42)
like image 437
Andrew Grimm Avatar asked Sep 05 '10 08:09

Andrew Grimm


3 Answers

Use:

x.should eq(42)

Or:

x.should be == 42

Or move x.should == 42 so that it's the last line inside the it block.


For those thinking BUT WHY?

I'm a complete noob to Ruby, but here is my understanding:

The warning comes from Ruby as statements like x.should == 42 or 1 == 1 return a value. If this return value is not actually used (eg. assigned to a variable, used as an argument to a function or returned from the block) then Ruby understandably sees no point of using the statement in the first place and alerts you to this.

To test this you can launch irb with the -w flag and add the following code:

> irb -w

def example
  1 == 1
  :hello
end

The 1 == 1 should issue a warning about useless == in void context. Try it without the :hello line and you won't get the warning as 1 == 1 would then be used as the return statement.

I know the Op and others here already understood this. However I wanted to post this for people like myself who may be wondering why the warning was being thrown and why the solutions proposed addressed this issue.

like image 137
Gerry Avatar answered Sep 22 '22 21:09

Gerry


RSpec-2 has an eq(expected) matcher that works just like == without the warning:

actual.should eq(expected) 
like image 43
David Chelimsky Avatar answered Sep 22 '22 21:09

David Chelimsky


You can also use actual.should be == expected. It simply depends on what you think looks prettier!

like image 35
Ivan Avatar answered Sep 19 '22 21:09

Ivan