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 を使用してテスト データをロードしています。で「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
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)

1 つの修正...:user_postファクトリでは、 のCommentオブジェクトの配列を作成する必要UserPost.commentがありますembeds_many。1つだけではありません。

于 2013-01-25T02:18:33.860 に答える