【发布时间】:2011-10-05 11:57:24
【问题描述】:
两个对象怎么可能看起来相同但实际上并不相同?
拥有运行代码“model!(owner).send(association).should == model!(target)”的pickle_step
在标签中运行时(黄瓜 --tags @thisonescenario),所有者和目标相同并且测试通过。
当与其余场景(黄瓜)一起运行时,所有者和目标不一样。
经过检查 (rdebug) 后,代码显示这些类并不相同,即使它们看起来确实如此。黄瓜步骤的输出如下:
expected: #<Content _id: content_1, _type: nil>
got: #<Content _id: content_1, _type: nil> (using ==)
Diff: (RSpec::Expectations::ExpectationNotMetError)
注意:== 被 Mongo 库重载,代码如下:
def ==(other)
self.class == other.class &&
attributes["_id"] == other.attributes["_id"]
end
_id 比较为真。 self.class== other.class 为假。
检查后代、祖先等类属性表明它们是相同的。
有什么想法吗?
【问题讨论】:
-
感谢您提供的信息。这是我对堆栈溢出如何工作的误解。我已经完成并做了接受答案的事情。
-
酷,现在
self.class == other.class应该将self.class.object_id与other.class.object_id进行比较 - 您可以在调试/测试中输出它们并查看它们是否相同? -
是的。这些在运行所有场景时是不同的,但在只运行一个场景时是相同的。此外,执行 self.class.ancestors 和 other.class.ancestors 显示了一个不同的模块(例如,这似乎是一些随机 id:#<0x00000105a11fe8>0x00000105a11fe8>
标签: ruby-on-rails class comparison equality mongodb