使用eq和eql在rspec测试中有什么区别?是否有区别:
it "adds the correct information to entries" do
# book = AddressBook.new # => Replaced by line 4
book.add_entry('Ada Lovelace', '010.012.1815', 'augusta.king@lovelace.com')
new_entry = book.entries[0]
expect(new_entry.name).to eq('Ada Lovelace')
expect(new_entry.phone_number).to eq('010.012.1815')
expect(new_entry.email).to eq('augusta.king@lovelace.com')
end
Run Code Online (Sandbox Code Playgroud)
和:
it "adds the correct information to entries" do
# book = AddressBook.new # => Replaced by line 4
book.add_entry('Ada Lovelace', '010.012.1815', 'augusta.king@lovelace.com')
new_entry = book.entries[0]
expect(new_entry.name).to eql('Ada Lovelace')
expect(new_entry.phone_number).to eql('010.012.1815')
expect(new_entry.email).to eql('augusta.king@lovelace.com')
end
Run Code Online (Sandbox Code Playgroud)
ste*_*tef 39
根据比较中使用的相等类型,这里存在细微差别.
来自Rpsec文档:
Ruby exposes several different methods for handling equality:
a.equal?(b) # object identity - a and b refer to the same object
a.eql?(b) # object equivalence - a and b have the same value
a == b # object equivalence - a and b have the same value with type conversions]
Run Code Online (Sandbox Code Playgroud)
eq使用==运算符进行比较,并eql忽略类型转换.
差异是细微的。eq是相同的Ruby实现的==。在另一方面eql是一样的Ruby实现的eql?。
eq检查对象的等效性,并将类型转换为将不同的对象转换为相同类型。如果两个对象属于同一类并且具有相同的值,但它们实际上不是相同的对象,则它们是等效的。
expect(:my_symbol).to eq(:my_symbol)
# passes, both are identical.
expect('my string').to eq('my string')
# passes, objects are equivalent
expect(5).to eq(5.0)
# passes, Objects are not equivalent but was type casted to same object type.
Run Code Online (Sandbox Code Playgroud)
eql 检查对象的等效性,并且不尝试类型转换。
expect(:my_symbol).to eql(:my_symbol)
# passes, both are identical.
expect('my string').to eql('my string')
# passes, objects are equivalent but not identical
expect(5).to eql(5.0)
# fails, Objects are not equivalence, did not tried to type cast
Run Code Online (Sandbox Code Playgroud)
equal检查对象身份。如果两个对象是相同的对象,则这两个对象是相同的,这意味着它们具有相同的对象ID(在内存中共享相同的地址)。
expect(:my_symbol).to equal(:my_symbol)
# passes, both are identical.
expect('my string').to equal('my string')
# fails, objects are equivalent but not identical
expect(5).to equal(5.0)
# fails, Objects are not equivalence and not identical
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13941 次 |
| 最近记录: |