I keep running into the same issue, and I would be surprised if I am the only person experiencing this and expect someone has a better way of doing this. When I create a Factory which has a dependent Factory (association), then the parent model is not updated with the model that has been added. Probably easier to explain in code.
Say I have:
Factory.define :company do |a|
a.name 'Acme'
end
Factory.define :office do |a|
a.name 'London'
a.association :company, :factory => :company
end
and I execute this code:
london = Factory.create(:office)
sanfran = Factory.create(:office, :name => 'San Fran' , :company = london.company)
then if I run this test
london.company.offices.count.should eql(2)
it fails, because company Acme was instantiated before London or even San Fran were created, and because company.offices.new was not used to create the new models, the company model was never updated.
The only way I have been able to work around this issue is to write my tests as follows:
london.company(true).offices.count.should eql(2)
which forces a refresh.
However, this is really not ideal to do this every time in my tests, especially when the code it is testing should not h开发者_如何学运维ave to rely on that.
Is there a reason you can't create the parent company first? I don't seem to have a problem getting a count from a pre-instantiated parent after creating child objects.
describe Company do
describe "office associations" do
before(:each) do
@company = Factory(:company)
end
it "should have the correct number of offices" do
o1 = Factory(:office, :company => @company)
o2 = Factory(:office, :company => @company)
@company.offices.should =~ [o1, o2].flatten # <= Not sure why, but each call to Factory appears to return an array
end
end
精彩评论