【问题标题】:How to load Factories for Embedded Models (Mongoid - Rails)如何为嵌入式模型加载工厂(Mongoid - Rails)
【发布时间】: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


【解决方案1】:

我认为您的问题是构建具有关联的对象。我们使用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 工厂中,您应该为UserPost.comment 创建一个Comment 对象数组,因为embeds_many。不只是一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多