[英]How to test mongoid scopes?
I defined the following User class with 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
If I use the following rspec test : 如果我使用以下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
I get the following fail message : 我收到以下失败消息:
got: #<Mongoid::Criteria
selector: {"role"=>:admin},
options: {:sort=>{"created_at"=>-1}},
class: User,
embedded: false>
So how could I test this scope ? 那我怎么测试这个范围呢?
Mongoid lazy loads, do: Mongoid延迟加载,请执行以下操作:
User.all_admins.recents.to_a.should eq([admin1, admin2])
Side notes: 旁注:
you should create your scopes as lambdas, it will soon be the norm with Rails4 您应该将自己的范围创建为lambda,它将很快成为Rails4的规范
I got issues with symbol type in mongo (during migrations), I'd rather use strings 我在mongo中遇到符号类型问题(在迁移过程中),我宁愿使用字符串
I'm pretty sure your test will fail since your objects are not created in db ( let
is not evaluated until it's called, replace with let!
) 我敢肯定,你的测试将失败,因为在数据库不创建你的对象( let
不计算,直到它的名字,代之以let!
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.