简体   繁体   English

rSpec - 如何在 model 方法中测试 select

[英]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.我有一个 model,它的方法只返回用户的名字和数量。

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?如何使用 rSpec 测试返回值?

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

The method returns an array of User objects, but with only two attributes.该方法返回一个用户对象数组,但只有两个属性。 This is where I'm stuck.这就是我卡住的地方。

Since .list returns incomplete Users, your best bet may be to pull out their attributes as a Hash:由于.list返回不完整的用户,您最好的选择可能是将其属性提取为 Hash:

User.list.map { |u| u.attributes }.
    should == [{ :firstname => "John", :qty => 10 }, { ... }]

factory_girl will DRY this right up: factory_girl会立即将其干燥:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM