Updating records with Factory Girl factory
Using RSpec and Factory Girl, I create a record that when created, has associated 'hours' records automatically created in after_create.
But I want to test with the non-default hours, preferably ones I define in factory girl factories. Here's what I'm thinking I'd like to do:
before (:all) do
@business = Fa开发者_Go百科ctory(:business_one)
# when that business is saved, a set of default hours is automatically saved as well
# how would I now update the hours with fixtures?
# so, ideally something like:
@business.hours[0] << Factory(:day_one)
@business.hours[1] << Factory(:day_two)
...etc...
end
Is this doable somehow or do I need to approach this differently?
Why not create an alternate factory:
Factory.define :business_with_altnernate_hours, :parent => :business_one do
after_create do |business|
business.hours.clear
Factory.create(:day_one, :business => business)
Factory.create(:day_two, :business => business)
end
end
This is what you can do:
@business = Factory(:business_one)
# clear associations so it's in a known state
@business.hours.clear
@business.hours << Factory(:day_one)
@business.hours << Factory(:day_two)
They will still be inserted and saved in the order in which you push in the new association.
精彩评论