Factory_girl - has_many 关系并刷新父模型
我不断遇到同样的问题,如果我是唯一遇到此问题的人并期望有人有更好的方法来做到这一点,我会感到惊讶。当我创建一个具有依赖工厂(关联)的工厂时,父模型不会使用已添加的模型进行更新。用代码解释可能更容易。
假设我有:
Factory.define :company do |a|
a.name 'Acme'
end
Factory.define :office do |a|
a.name 'London'
a.association :company, :factory => :company
end
并且我执行此代码:
london = Factory.create(:office)
sanfran = Factory.create(:office, :name => 'San Fran' , :company = london.company)
那么如果我运行此测试,
london.company.offices.count.should eql(2)
它将失败,因为公司 Acme 在创建伦敦甚至旧金山之前就已实例化,并且因为 company.offices.new 没有用于创建新模型,所以公司模型从未更新。
我能够解决此问题的唯一方法是按如下方式编写测试:
london.company(true).offices.count.should eql(2)
这会强制刷新。
然而,在我的测试中每次都这样做确实并不理想,特别是当它正在测试的代码不必依赖它时。
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 have to rely on that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有什么理由不能先创建母公司吗?在创建子对象后,从预实例化的父级获取计数似乎没有问题。
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.