5

そのため、Mongoid、Rspec、Factory_Girlで遊んでいて、埋め込みドキュメントでいくつか問題が発生しました。

私は次のモデルを持っていました:

class Profile    
   include Mongoid::Document

   #Fields and stuff
      embeds_one :address

   validates :address, presence: true 
end

class Address    
   include Mongoid::Document

   #Fields and stuff
      embedded_in :profile 
end

したがって、このようなファクトリを定義すると、次のようになります。

FactoryGirl.define do
  factory :profile do
    #fields

    address
  end
end

次のようなエラーが発生しました:

Failure/Error: subject { build :profile }
     Mongoid::Errors::NoParent:

       Problem:
         Cannot persist embedded document Address without a parent document.
       Summary:
         If the document is embedded, in order to be persisted it must always have a reference to it's parent document. This is most likely cause by either calling Address.create or Address.create! without setting the parent document as an attribute.
       Resolution:
         Ensure that you've set the parent relation if instantiating the embedded document direcly, or always create new embedded documents via the parent relation.

工場を次のように変更することで機能しました。

FactoryGirl.define do
  factory :profile do
    #fields

    after(:build) do |p| 
      p.create_address(FactoryGirl.attributes_for(:address))
    end
  end
end

これは機能しますが、これを行うためのよりネイティブなFactory_Girlの方法があることを望んでいます。あるべきだと思われます。

前もって感謝します!

4

2 に答える 2

11

Factory Girl + Mongoidのフィクスチャ内の埋め込みドキュメントで参照されているように、この方法でも実行できます。

FactoryGirl.define do
  factory :profile do |f|
    #fields
    address { FactoryGirl.build(:address) }
  end
end
于 2013-01-16T17:18:51.553 に答える
3

build_addressの代わりに使用してみてくださいcreate_address。私の意見では、プロファイルレコードが永続化(作成)される前にアドレスレコードを作成しようとしているため、ファクトリが壊れています。build_*必要なすべての属性を親モデルに割り当て、後で埋め込み関係とともに永続化する必要があります。

于 2012-10-15T18:53:15.780 に答える