Has_Many While Respecting Build Strategy in Factory_Girl

has_many while respecting build strategy in factory_girl

I wrote it properly with inheritance and all that. My commits are merged in here and here.

It's now in FactoryGirl 1.2.3, woot!

FactoryGirl: Populate a has many relation preserving build strategy

Here's a slightly cleaner version of Flipstone's answer:

factory :offering do
trait :stay do
...
photos do
association :hotel_photo, :strategy => @build_strategy.class
end
end
end

How to set up factory in FactoryBot with has_many association

Creating these kinds of associations requires using FactoryGirl's callbacks.

A perfect set of examples can be found here.

https://thoughtbot.com/blog/aint-no-calla-back-girl

To bring it home to your example.

Factory.define :listing_with_features, :parent => :listing do |listing|
listing.after_create { |l| Factory(:feature, :listing => l) }
#or some for loop to generate X features
end

Populating an association with children in factory_girl

The Factory.after_ hooks appear to be the only way to do this successfully. I've figured out a way to maintain the build strategy without duplicating code:

Factory.define :foo do |f|
f.name "A Foo"
f.after(:build) { |foo|
foo.bars << Factory.build(:bar, :foo => foo)
}
f.after(:create) { |foo|
foo.bars.each { |bar| bar.save! }
}
end

The documentation states that after_build will be called before after_create if the :create build strategy is used. If :build is used, then only after_build is called, and everyone is happy.

I've also created an abstracted generally-applicable version at this gist to keep things DRY.

DRYer tests with associations in factory_girl

I don't know if this is what you're looking for, but if you first create message you can fetch the sender through that and assign it to @me.

@my_message = Factory(:message)
@me = @my_message.sender

Does that help at all?



Related Topics



Leave a reply



Submit