在`expect`测试中,Rspec`eq`对`eql`

aus*_*ing 29 ruby rspec

使用eqeql在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忽略类型转换.

  • @austinthesing它意味着`42.0 == 42`产生'true`和'42.0.eql?42`产生'假'. (9认同)
  • 需要注意的是,类型不是从字符串转换而来的。所以如果你比较 `"1" == 1`,它总是返回 `false` (3认同)

Far*_*ain 9

差异是细微的。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)

  • 我愚蠢的助记符是方法名称越长,比较越严格:`eq` < `eql` < `equal` (15认同)