-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using factories having multiple associations to the same model #382
Comments
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! |
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? |
@ashrafuzzaman I think you actually want to create the speech in factory :published_event do
published true
after_create do |published_event|
create(:speech, :event => published_event)
end
end |
Thanks I will try that and let you know :) |
@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! |
Thanks it worked :) |
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:
In my factory file I have:
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?
The text was updated successfully, but these errors were encountered: