Factory_bot: 同じモデルに複数の関連付けがあるファクトリを使用する

作成日 2012年05月18日  ·  6コメント  ·  ソース: thoughtbot/factory_bot

Ruby on Rails 3.2.2、FactoryGirl 3.1.0、FactoryGirlRails3.1.0を使用しています。 別のモデルに2つの関連付けがあるモデルがあります。

class Article < ActiveRecord::Base
  belongs_to a_users, :class_name  => 'User'
  belongs_to b_users, :class_name  => 'User'
end

私のファクトリファイルには次のものがあります。

factory :article, :class => Article do
  title "Sample title"

  association :a_users, factory: :user
  association :b_users, factory: :user
end

上記のコードを使用すると、2人のユーザーが作成されますが、_両方の関連付けに同じユーザーが必要です_(複数のユーザーを作成する必要はありません)。 どうすればそれを作ることができますか?

最も参考になるコメント

私はあなたができると思います:

factory :article do
  title 'Sample title'

  association :a_users, factory: :user
  b_users { a_users }
end

それがどうなるか教えてください!

全てのコメント6件

私はあなたができると思います:

factory :article do
  title 'Sample title'

  association :a_users, factory: :user
  b_users { a_users }
end

それがどうなるか教えてください!

こんにちは私は同様の質問があります。 モンゴイドを使用しています。 私のシナリオは、

class User
  include Mongoid::Document
  has_many :events
end

class Event
  include Mongoid::Document
  has_many :speeches
end

class Speech
  include Mongoid::Document
  belongs_to :event
  belongs_to :user
end

私は試した、

FactoryGirl.define do
  factory :organizer, class: User do
    events {|events| [events.association(:published_event)]}
  end

  factory :event, class: Event do
    name 'Published event'
    ...
    factory :published_event do
      published true
      speeches {|event| [event.association(:speech)]}
    end
  end

  factory :speech, class: Speech do
    name 'Speech 1'
    after_build { |speech| speech.user = speech.event.user }
  end
end

そしてそれを次のように使用しました

FactoryGirl.create(:organizer)

音声ビルダーのafter_buildにnullポインターが表示されます。 Speech.eventはnilです。 実際、私のシナリオはもっと複雑で、単純に抽象化したものです。 すでに作成されている場合、既存のデータをリードするためのソリューションはファクトリーガールにありますか?

@ashrafuzzaman after_createコールバックでpublished_eventのスピーチを実際に作成し、そのスピーチにイベントを割り当てたいと思います。

factory :published_event do
  published true

  after_create do |published_event|
    create(:speech, :event => published_event)
  end
end

ありがとう私はそれを試してあなたに知らせます:)

@ashrafuzzaman運がいいですか? とりあえずこれを閉じますが、それでも問題が解決しない場合は、もう一度開いたり、別のチケットを提出してください。 ありがとう!

それが働いてくれてありがとう:)

このページは役に立ちましたか?
0 / 5 - 0 評価