问题描述
在的Ruby 1.9.2
在的Rails 3.0.3
,我试图测试的对象相等两个朋友
(类继承自的ActiveRecord :: Base的
)的对象。
In Ruby 1.9.2
on Rails 3.0.3
, I'm attempting to test for object equality between two Friend
(class inherits from ActiveRecord::Base
) objects.
该对象是相等的,但测试失败:
The objects are equal, but the test fails:
Failure/Error: Friend.new(name: 'Bob').should eql(Friend.new(name: 'Bob'))
expected #<Friend id: nil, event_id: nil, name: 'Bob', created_at: nil, updated_at: nil>
got #<Friend id: nil, event_id: nil, name: 'Bob', created_at: nil, updated_at: nil>
(compared using eql?)
只是为了笑着,我也测试对象的身份,从而未能如我所料:
Just for grins, I also test for object identity, which fails as I'd expect:
Failure/Error: Friend.new(name: 'Bob').should equal(Friend.new(name: 'Bob'))
expected #<Friend:2190028040> => #<Friend id: nil, event_id: nil, name: 'Bob', created_at: nil, updated_at: nil>
got #<Friend:2190195380> => #<Friend id: nil, event_id: nil, name: 'Bob', created_at: nil, updated_at: nil>
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
'actual.should == expected' if you don't care about
object identity in this example.
有人能向我解释为什么对象平等第一次测试失败,我怎样才能成功地断言这两个对象是相等的?
Can someone explain to me why the first test for object equality fails, and how I can successfully assert those two objects are equal?
推荐答案
Rails的故意代表平等检查标识列。如果你想知道如果两个AR对象包含同样的东西,比较呼吁双方#attributes的结果。
Rails deliberately delegates equality checks to the identity column. If you want to know if two AR objects contain the same stuff, compare the result of calling #attributes on both.
这篇关于如何测试(ActiveRecord的)对象相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!