Brian Armstrong
Brian Armstrong

Reputation: 19873

Mongoid == (equals) operator not working as expected

Sometimes in my tests I compare two user objects:

transaction.sender.should == user1

And Rspec gives me some output showing that the objects have the same id (and other params) but have a different object 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>.==.

I'm not sure why this is. I assume the user ids shown on the diff line mean it's a different instance of the object, but Mongoid should check the _id param for equality right?. I'm using Mongoid 2.4.12.

I thought maybe this would help if the object was out of date but same results:

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

I've take to doing this for now but it's worrying me that maybe something else is going on.

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

Thanks!

Upvotes: 0

Views: 455

Answers (1)

modetojoy
modetojoy

Reputation: 166

Mongoid checks equality by checking the classes are the same first, then checking the ids.

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

If this is failing, I suspect something else is overriding Document#== and I would grep your gems to see if that is the case.

Upvotes: 3

Related Questions