Mongoid ==(等于)运算符未按预期工作

时间:2012-08-19 09:26:39

标签: rspec mongoid

有时在我的测试中我会比较两个用户对象:

transaction.sender.should == user1

Rspec给了我一些输出,显示对象具有相同的id(和其他参数)但具有不同的对象id:

 Failure/Error: tx.sender.reload.should == @u1.reload
   expected: #<User _id: 5030afb4f8182bb3a9000005, ...>
        got: #<User _id: 5030afb4f8182bb3a9000005, ...> (using ==)
   Diff:#<User:0x007fc0c7e56cf0>.==(#<User:0x007fc0c7ec53f8>) returned false even though the diff between #<User:0x007fc0c7e56cf0> and #<User:0x007fc0c7ec53f8> is empty. Check the implementation of #<User:0x007fc0c7e56cf0>.==.

我不确定为什么会这样。我假设diff行上显示的用户ID意味着它是对象的不同实例,但是Mongoid应该检查_id param的相等性吗?我正在使用Mongoid 2.4.12。

我想如果对象过时但结果相同,这可能会有所帮助:

transaction.sender.reload.should == user1.reload

我现在已经开始这样做,但令我担心的是,可能正在发生其他事情。

transaction.sender.id.should == user1.id

谢谢!

1 个答案:

答案 0 :(得分:3)

Mongoid通过首先检查类是否相同来检查等式,然后检查ID。

https://github.com/mongoid/mongoid/blob/master/lib/mongoid/document.rb#L37

如果失败了,我怀疑还有其他东西覆盖了文档#==我会看到你的宝石,看看是不是这样。