为什么我在 rspec 中得到的是 Active record 关系而不是 Array?

Ors*_*say 3 rspec ruby-on-rails

我正在运行测试Post

expect(subject.query).to eq [previous_post, post, future_comment]

但我收到这个错误:

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.....>]>
Run Code Online (Sandbox Code Playgroud)

它需要一个数组,但得到一个活动记录对象。我该如何解决这个问题?

这是我正在测试的代码:

      def query
        scope = Post
                .where(user_id: user.id)
                .my_scope
                .my_other_scope
                .includes(:body)

        scope = case @options[:order_by]
                when "older"
                  order_by_older(scope)
                when "most_discussed"
                  order_by_most_discussed(scope)
                else
                  order_by_older(scope)
                end

        scope
      end
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以更新您的规格来使用。

expect(subject.query).to contain_exactly(previous_post, post, future_comment)
Run Code Online (Sandbox Code Playgroud)

如果它是代码中的依赖项,那么您可以使用 .to_a@MrYoshiji 提到的方法将其转换为数组

如果可以避免的话,我不建议将其转换为数组,原因是速度较慢。