当两件事相等时,RSpec eq 匹配器返回失败 [英] RSpec eq matcher returns failure when two things are equal
问题描述
在我的控制器测试中,我正在测试分配给实例变量的正确值.
In my controller test, I am testing the correct value is assigned to an instance variable.
当我这样做
expect(assigns(:conversations)).to eq @user_inbox
RSpec 告诉我:
Failure/Error: expect(assigns(:conversations)).to eq @user_inbox
expected: #<ActiveRecord::Relation [#<Mailboxer::Conversation id: 4, subject: "Dude, what up?", created_at: "2014-10-21 08:43:50", updated_at: "2014-10-21 08:43:50">]>
got: #<ActiveRecord::Relation [#<Mailboxer::Conversation id: 4, subject: "Dude, what up?", created_at: "2014-10-21 08:43:50", updated_at: "2014-10-21 08:43:50">]>
(compared using ==)
Diff:
我发现预期和实际之间没有区别.我想知道是什么导致此测试失败.
I see that there is no difference between the expected and the actual. I would like to know what is causing this test to fail.
推荐答案
ActiveRecord::Relation
比较基于实际关系,而不是结果集.例如,
ActiveRecord::Relation
compares based on the actual relation, not the result set. For example,
User.where(:id => 123) == User.where(:email => "fred@example.com")
会返回false,即使查询结果相同,因为实际查询不同.
will return false, even the query results are both the same, since the actual queries are different.
我怀疑您更关心查询结果而不是它的组成方式,在这种情况下,您可以使用 to_a
将关系转换为活动记录对象数组.请注意,Active Record 仅根据 id
属性的值定义相等性(未保存对象的特殊情况).
I suspect that you care much more about the query results rather than how it was composed, in which case you can use to_a
to convert the relation to an array of active record objects. Note that Active Record defines equality based only on the value of the id
attribute (with a special case for unsaved objects).
这篇关于当两件事相等时,RSpec eq 匹配器返回失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!