简体   繁体   中英

Testing named_scope with Mongoid and rspec

I'm newbie in RoR, and I am trying to test a simple named_scope for my Model.

But I don't know if I have a problem in my model (I'm using mongoid), in my code test (I'm using rspec) or in my factory. I got this error

Mongoid::Errors::InvalidCollection: Access to the collection for Movement is not allowed since it is an embedded document, please access a collection from the root document.

My models

class Movement
    include Mongoid::Document
    field :description, :type => String
    embedded_in :category

    named_scope :top, lambda { |number| { :limit => (number.size > 0 ? number : 10) } }    
end

class Category
  include Mongoid::Document
  field :name
  embeds_many :movement
end

My factory, con factory_girl

Factory.define :movement do |m|
  m.amount 24
  m.date "30/10/2011"
  m.description "Beer"
  m.association :category, :factory => :category
end

Factory.define :category do |c|
  c.name "Drink"
end

My test

describe "when i have a movement list" do
  it "recent method should return last 2 movements" do
    @movements = (1..3).collect { Factory(:movement) }
    recent_movements = Movement.top(2)
    recent_movements.should have(2).entries
  end
end

And the error:

Mongoid::Errors::InvalidCollection: Access to the collection for Movement is not allowed since it is an embedded >document, please access a collection from the root document.

I tried a little change in my factory.

   Factory.define :movement do |m|
      m.amount 24
      m.date "30/10/2011"
      m.description "Beer" 
      m.category { [ Factory.build(:category) ] }
    end

But then I got other different error:

Failure/Error: @movements = (1..3).collect { Factory(:movement) } NoMethodError: undefined method `reflect_on_association' for #

Could someone help me?

Thanks

I just had a the same error in my app. I ended up having an error in my class and that solved my problem.

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.

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