2012-12-15 75 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

哪一个最适合阵列? –

相关问题