Ruby on rails 为什么在rspec中获取活动记录关系而不是数组?
我正在Ruby on rails 为什么在rspec中获取活动记录关系而不是数组?,ruby-on-rails,rspec,Ruby On Rails,Rspec,我正在Post上运行测试: expect(subject.query).to eq[以前的帖子、帖子、将来的评论] 但我得到了这个错误: expected: [#<Post id: 3, body: "Sed quis aut harum. Asperiores ad commodi tempore ...", ...>] got: #<ActiveRecord::Relation [#<Post id: 3, body: "Sed quis aut harum. A
Post
上运行测试:
expect(subject.query).to eq[以前的帖子、帖子、将来的评论]
但我得到了这个错误:
expected: [#<Post id: 3, body: "Sed quis aut harum. Asperiores ad commodi tempore ...", ...>]
got: #<ActiveRecord::Relation [#<Post id: 3, body: "Sed quis aut harum. Asperiores a.....>]>
这是因为您使用的是
where
,而不是find
或find\u by
,当使用where时,无论查询是否返回一个或多个结果,您都会得到一个ActiveRecord::Relation
作为结果-响应
如果您需要一个POST对象,则考虑使用<代码>查找< /代码>,或者如果使用<代码>在中,请确保在内部指定任何特定元素。
您可以尝试(未测试):您可以更新您的等级库以使用
expect(subject.query).to contain_exactly(previous_post, post, future_comment)
如果它是代码中的依赖项,那么可以使用
.to_a
如@MrYoshiji所述
如果可以避免的话,我不建议将其转换为数组,原因是它速度较慢。实际上,我希望得到多篇文章,而不仅仅是一篇。那么,最好的方法应该是哪里,你所说的“指定内部的任何特定元素”是什么意思?所谓内部的特定元素,我指的是索引,与结果中的索引相对应的任何元素。对不起,我不理解:/Finder返回集合的方法,例如where和group,返回ActiveRecord::Relation的实例。查找单个实体的方法(如find和first)返回模型的单个实例。如果您需要一个包含不同对象的数组,Yoshiji先生的评论可能会有所帮助。您可以执行
subject.query.to\u a
您希望您的方法专门返回数组吗?有依赖关系吗?。正如有人已经提到的,where返回活动记录关系
def scope(user_id)
Post.find_by(user_id: user_id).my_scope.my_other_scope.includes(:body)
end
def query(user_id)
order = @options[:order_by]
return order_by_older(scope(user_id)) if order == 'older'
return order_by_most_discussed(scope(user_id)) if order == 'most_discussed'
order_by_older(scope(user_id))
end
expect(subject.query).to contain_exactly(previous_post, post, future_comment)