2013-01-23 68 views
0

我使用Mongoid在我的Rails應用程序,考慮我有下面的字段命名爲「郵報」一類具有以下結構如何加載嵌入模型工廠(Mongoid - Rails)的

class UserPost 

    include Mongoid::Document 
    field :post, type: String 
    field :user_id, type: Moped::BSON::ObjectId 
    embeds_many :comment, :class_name => "Comment" 

    validates_presence_of :post, :user_id 

end 

- 插入值時

class Comment 

    include Mongoid::Document 
    field :commented_user_id, type: Moped::BSON::ObjectId 
    field :comment, type: String 

    embedded_in :user_post, :class_name => "UserPost" 

end 

這種模式可以完美運行。

但現在我正在爲此模型編寫測試,我使用Factory女孩來加載測試數據。我很困惑,我可以如何繪製出「UserPost」模型下的模型字段 /spec/factories/user_posts.rb

我試着用下面的格式,但它不工作(僅限某些字段添加例如)

FactoryGirl.define do 

    factory :user_post do 
    id Moped::BSON::ObjectId("50ffd609253ff1bfb2000002") 
    post "Good day..!!" 
    user_id Moped::BSON::ObjectId("50ffd609253ff1bfb2000002") 
    comment :comment 
    end 

    factory :comment do 
    id Moped::BSON::ObjectId("50ffd609253ff1bfb2000002") 
    end 

end 
+0

你爲什麼硬編碼ids?它的例如 – apneadiving

+0

..我應該如何定義工廠沒有硬編碼? – balanv

回答

0

我認爲你的問題是建立與對象的關聯。我們使用ignore塊來解決這個問題,以延遲建立關聯。

FactoryGirl.define do 

    # User factory 
    factory :user do 
    # ... 
    end 

    # UserPost factory 
    factory :user_post do 

    # nothing in this block gets saved to DB 
    ignore do 
     user { create(:user) } # call User factory 
    end 

    post "Good day..!!" 

    # get id of user created earlier 
    user_id { user.id } 

    # create 2 comments for this post 
    comment { 2.times.collect { create(:comment) } } 
    end 
end 

# automatically creates a user for the post 
FactoryGirl.create(:user_post) 

# manually overrides user for the post 
user = FactoriGirl.create(:user) 
FactoryGirl.create(:user_post, user: user) 

一個補丁修復......在:user_post工廠,你應該創建Comment對象的數組,UserPost.comment因爲embeds_many。不只是一個。