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
How to Validate Members of an Array Field
Jekyll - Generating JSON Files Alongside the HTML Files
Why Are My Bigdecimal Objects Initialized with Unexpected Rounding Errors
How to Share the Factories That I Have in a Gem and Use It in Other Project
Rbenv Irb History Is Not Saving
While Executing Gem, Unknown Command
Preload Has_Many Associations with Dynamic Conditions
How to Backreference in Ruby Regular Expression (Regex) with Gsub When I Use Grouping
How to Get My MAChine's Ip Address from Ruby Without Leveraging from Other Ip Address
How to Reverse Ruby's Include Function
How to Add MAC-Specific Gems to Bundle on MAC But Not on Linux
Match String That Doesn't Contain a Specific Word
Access Instance Variable from Outside the Class
Undefined Instance Method "Respond_To" in Rails 5 API Controller
How Would I Save Multiple Records at Once in Rails
Can Bundler Show Me Which Gems in Gemfile Have Newer Versions (Eg. Dry-Run of Bundle Update)