I defined the following User class with scopes :
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 :
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:
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
I got issues with symbol type in mongo (during migrations), I'd rather use strings
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!
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.