Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Using factories having multiple associations to the same model #382

Closed
Backoo opened this Issue · 6 comments

3 participants

@Backoo

I am using Ruby on Rails 3.2.2, FactoryGirl 3.1.0 and FactoryGirlRails 3.1.0. I have a model that has two association to another model:

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

In my factory file I have:

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

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

By using the above code it will create two users, but I would like that both associations have the same user (without to create multiple users). How can I make that?

@joshuaclayton

I think you'd be able to do:

factory :article do
  title 'Sample title'

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

Let me know how that turns out!

@ashrafuzzaman

Hi I have a similar question. I am using mongoid. My scenario is,

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

I tried,

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

And used it like,

FactoryGirl.create(:organizer)

It gives me null pointer in after_build of the speech builder. speech.event is nil. Actually my scenario is more complex and I made a simple abstraction of it. Is there a solution in the factory girl to lead existing data if already created?

@joshuaclayton

@ashrafuzzaman I think you actually want to create the speech in published_event in an after_create callback and assign the event to the speech:

factory :published_event do
  published true

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

Thanks I will try that and let you know :)

@joshuaclayton

@ashrafuzzaman any luck? I'm going to close this for now, but feel free to reopen or file another ticket if you're still having some issues. Thanks!

@ashrafuzzaman

Thanks it worked :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.