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?
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 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
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 :)
Most helpful comment
I think you'd be able to do:
Let me know how that turns out!