Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rSpec - how to test select inside a model method

I have a model with a method that returns just the first name of a user and a qty.

class User < ActiveRecord::Base
  def self.list
    select("firstname, qty").order("qty desc").all
  end
end

how would I test the return value with rSpec?

User.list.should == [?????]

The method returns an array of User objects, but with only two attributes. This is where I'm stuck.

like image 895
robzolkos Avatar asked Jul 30 '26 05:07

robzolkos


2 Answers

Since .list returns incomplete Users, your best bet may be to pull out their attributes as a Hash:

User.list.map { |u| u.attributes }.
    should == [{ :firstname => "John", :qty => 10 }, { ... }]
like image 78
Rob Davis Avatar answered Aug 01 '26 20:08

Rob Davis


factory_girl will DRY this right up:

fewer_qty_user = Factory.create(:blank_user, :qty => 100, :firstname => 'Bob')
more_qty_user  = Factory.create(:blank_user, :qty => 200, :firstname => 'Alice')
User.list.should == [more_qty_user, fewer_qty_user]
like image 41
John Feminella Avatar answered Aug 01 '26 18:08

John Feminella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!