2012-12-15 82 views
3

開始使用rspec斷言和黃瓜,我對使用字符串比較的方式有疑問。我已經嘗試了以下4種方法,它們都能產生相同的結果,所以我想知道其中一種方法是否比其他方法更好?Rspec比較:should eq,match,be,==之間的區別?

而且,很容易解釋4種方法之間的區別嗎?也許有一個例子?

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') 

非常感謝!

回答

3

對於你所做的字符串比較,==eq(be .)基本上是一樣的。

match的是模式匹配和將匹配諧音,因此將匹配bRadiosity這不會對其他的方法真,如果這是在a錨標籤

例如整個文本

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

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"> 

注:

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

個人而言,我喜歡==最好的字符串比較。其他人更喜歡.eql,因爲它與=的差異更大(突出更多,更少混淆)。我可能更喜歡==,因爲它可以跨語言更方便地移植。

+0

嗨邁克爾,感謝您的解釋。在任何情況下,這些運算符'==,eq,(be。)'之間是否有區別,即在哪些特定情況下我們應該使用其中的一種來確保我們獲得正確的行爲? – mickael

+0

有關其他信息,請參閱http://discuss.joelonsoftware.com/default.asp?joel.3.687916.13。 –

+0

哪一個最適合陣列? –

相關問題