概要
(Rspec内で) FactoryGirl を使って Mongoid::Document を createすると
Mongo::Error::OperationFailure:
みたいなエラーが出る
E11000 duplicate key error index: myapp_test.users.$_id_ dup key: { : ObjectId('56f1928569abcf62dfacdc41') } (11000)
原因?
cascade_callbacks:true にした関連オブジェクトをsaveより前に参照させると起きる。以下のどの方法でも発生する。
(FactoryGirl内で、belongs_to/has_manyにせよembeds_one/manyにせよ、参照を持たせると発生する。 以下のような感じ。)
class User
include Mongoid::Document
include Mongoid::Timestamps
embeds_one :profile, cascade_callbacks: true
end
class Profile
include Mongoid::Document
embedded_in :user
end
factory :user do
profile{ build(:profile) }
end
# こっちでもダメ
factory :user do
after(:build) do |u|
u.profile = build(:profile)
end
end
対策
- cascade_callbacks をなるべく使わない
- cascade_callbacks を使う場合、
after(:create) do ~~ end
の中で関連オブジェクトを入れる。 (buildだと関連オブジェクトが入らないのは諦め、場当たり的に都度対応する。)