0

我在我的 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 来加载测试数据。我对如何/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
4

1 回答 1

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.commentembeds_many

于 2013-01-25T02:18:33.860 回答