Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec comparisons: difference between should eq, match, be, ==?

Tags:

rspec

Starting to use rspec assertions with cucumber and I've got the doubt about which way to make string comparisons. I've tried the following 4 methods and all of them seem to produce the same result, so I was wondering if one of the methods is better over the others?

And, is it easy to explain the difference between the 4 methods? Maybe with an example?

page.first('div#navigation a').text.should == 'Radio')
page.first('div#navigation a').text.should eq('Radio')
page.first('div#navigation a').text.should match('Radio')
page.first('div#navigation a').text.should (be 'Radio')

Many thanks!!

like image 316
mickael Avatar asked Dec 15 '12 15:12

mickael


1 Answers

For the string comparison you are doing, == , eq and (be .) are basically the same.

The match is pattern matching and will match partials, so would match bRadiosity which would not be true for the other methods if that was the whole text in the a anchor tag

e.g.

1.9.3-p194 :001 > a="text with radio"
 => "text with radio" 
1.9.3-p194 :002 > a.=='radio'
 => false 

and

1.9.3-p194 :013 > b="radioz"
 => "radioz" 
1.9.3-p194 :014 > b.=="radio"
 => false 
1.9.3-p194 :015 > b.match "radio"
 => #<MatchData "radio"> 

Note:

== is ruby (which also has .eql? available though not shown here).
.eq is an rspec helper as is the (be .) construct

Personally I like == the best for string comparison. Other folks prefer .eql because it differs more from = (stands out more, less confusion). I may like == more as it sems a bit more portable across languages.

like image 107
Michael Durrant Avatar answered Nov 18 '22 19:11

Michael Durrant