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

时间:2015-10-03 19:50:29

标签: ruby rspec

在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

2 个答案:

答案 0 :(得分:33)

这里有一些细微差别,基于比较中使用的相等类型。

来自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]

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

答案 1 :(得分:1)

差异是细微的。eq==的{​​{3}}相同,而eqleql?的{​​{3}}相同,如上所述rspec-expectaion宝石。

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. 

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 case

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
相关问题