【发布时间】:2013-01-23 12:52:57
【问题描述】:
我在我的 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
【问题讨论】:
-
为什么要对 ID 进行硬编码?
-
它的例子..我应该如何定义没有硬编码的工厂?
标签: ruby-on-rails mongoid factory-bot