LoginSignup
2
2

More than 5 years have passed since last update.

FacotoryGirl で Mongoid::Document をcreateしたりsaveしたりすると E11000 duplicate key error index が起きる件

Last updated at Posted at 2016-03-23

概要

(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

対策

  1. cascade_callbacks をなるべく使わない
  2. cascade_callbacks を使う場合、 after(:create) do ~~ end の中で関連オブジェクトを入れる。 (buildだと関連オブジェクトが入らないのは諦め、場当たり的に都度対応する。)
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2