代码之家  ›  专栏  ›  技术社区  ›  obo

如何测试mongoid示波器?

  •  0
  • obo  · 技术社区  · 13 年前

    我定义了以下具有作用域的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>
    

    那么我该如何测试这个范围呢?

    1 回复  |  直到 13 年前
        1
  •  1
  •   apneadiving    13 年前

    Mongoid懒惰加载,执行:

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

    旁注:

    • 你应该将你的作用域创建为lambdas,这很快就会成为Rail4的常态

    • 我在mongo中遇到了符号类型问题(在迁移过程中),我宁愿使用字符串

    • 我很确定你的测试会失败,因为你的对象不是在数据库中创建的( let 在调用之前不会进行求值,替换为 let! )