簡體   English   中英

如何測試蒙古范圍?

[英]How to test mongoid scopes?

我用范圍定義了以下User類:

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Search

  # SCOPES
  scope :all_admins, where( role: :admin)
  scope :recents, order_by(created_at: :desc)
  scope :olders, order_by(created_at: :asc)

  field :role, type: Symbol
end

如果我使用以下rspec測試:

describe 'scopes' do
  let(:admin1)            { Fabricate(:admin) }
  let(:admin2)               { Fabricate(:admin) }

  describe 'recents' do
    it 'should return the admins from most recent to older' do
      User.all_admins.recents.should eq([admin1, admin2])
    end
  end
end

我收到以下失敗消息:

got: #<Mongoid::Criteria
  selector: {"role"=>:admin},
  options:  {:sort=>{"created_at"=>-1}},
  class:    User,
  embedded: false>

那我怎么測試這個范圍呢?

Mongoid延遲加載,請執行以下操作:

User.all_admins.recents.to_a.should eq([admin1, admin2])

旁注:

  • 您應該將自己的范圍創建為lambda,它將很快成為Rails4的規范

  • 我在mongo中遇到符號類型問題(在遷移過程中),我寧願使用字符串

  • 我敢肯定,你的測試將失敗,因為在數據庫不創建你的對象( let不計算,直到它的名字,代之以let!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM