2015-10-03 44 views
17

?有没有之间的差异:rspec测试中使用<code>eq</code>和<code>eql</code>时,Rspec`eq`和`eql`测试

it "adds the correct information to entries" do 
    # book = AddressBook.new # => Replaced by line 4 
    book.add_entry('Ada Lovelace', '010.012.1815', '[email protected]') 
    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('[email protected]') 
end 

和:

it "adds the correct information to entries" do 
    # book = AddressBook.new # => Replaced by line 4 
    book.add_entry('Ada Lovelace', '010.012.1815', '[email protected]') 
    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('[email protected]') 
end 

回答

23

这里有细微的差别,建立在平等的类型,在比较中使用。

从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忽略类型转换。

+0

类型转换是否意味着它正在寻找被比较的对象或事物是相同类型的对象? – austinthesing

+5

@austinthesing它意味着'42.0 == 42'产生'true'和'42.0.eql? 42'产生'false'。 –