在“expect”测试中指定“eq”与“eql”



在rspec测试中使用eqeql有什么区别?

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

:

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

根据在比较中使用的相等类型,这里有细微的区别。

From the Rpsec docs:

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]

eq使用==运算符进行比较,eql忽略类型转换。

差别很细微。eq==的ruby实现相同。另一方面,eqleql?的ruby实现相同。

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 cast to same object type. 

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 try to type cast

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 equivalent and not identical

最新更新