Orsay
Orsay

Reputation: 1130

Why do I get Active record relation instead of Array in rspec?

I'm running tests on Post:

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

But I get this error :

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.....>]>

It expected an array but get an active record object. How can I resolve that ?

This is the code i'm testing :

      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

Upvotes: 3

Views: 4565

Answers (2)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

That's because you're using where, instead find or find_by, when using where then you get an ActiveRecord::Relation as result - response, no matter if the query returns one or more results.

If you need a single Post object then consider using find, or in case using where, make sure of specifying any specific element inside.

You could try with (not tested):

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

Upvotes: 3

a131
a131

Reputation: 564

you can update your spec to use.

expect(subject.query).to contain_exactly(previous_post, post, future_comment)

If its a dependency in your code then you can convert it to an array using .to_a as mentioned by @MrYoshiji

I do not recommend converting it to an array if it can be avoided, reason being it slower.

Upvotes: 5

Related Questions