我在我的Rails应用程序中使用Mongoid,考虑我在名为“Post”的类中具有以下字段,结构如下
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 girl来加载测试数据。我对如何绘制“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 :(得分: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
个对象数组。不只是一个。