工厂女孩/机械师中的单例工厂?
工厂女孩/机械师的工厂中是否有某种配置,强制其在测试用例期间仅创建一次具有相同工厂名称的对象,并始终返回相同的实例?我知道,我可以做类似的事情:
def singleton name
@@singletons ||= {}
@@singletons[name] ||= Factory name
end
...
Factory.define :my_model do |m|
m.singleton_model { singleton :singleton_model }
end
但也许有更好的方法。
Is there some configuration in a factory of factory girl/machinist that forces it to create objects with the same factory name just once during test case and return the same instance all the time? I know, i can do something like:
def singleton name
@@singletons ||= {}
@@singletons[name] ||= Factory name
end
...
Factory.define :my_model do |m|
m.singleton_model { singleton :singleton_model }
end
but maybe there is a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在工厂内使用
initialize_with
宏并检查该对象是否已存在,然后不要再次创建它。当所述工厂被关联引用时,这也适用:这里有一个类似的问题,有更多替代方案: 在 Rails 中将factory_girl 与具有唯一约束的关联一起使用。出现重复错误
You can use the
initialize_with
macro inside your factory and check to see if the object already exists, then don't create it over again. This also works when said factory is referenced by associations:There is a similar question here with more alternatives: Using factory_girl in Rails with associations that have unique constraints. Getting duplicate errors
@CubaLibre 用 FactoryBot 版本 5 回答:
@CubaLibre answer with version 5 of FactoryBot:
不确定这对您是否有用。
通过此设置,您可以使用工厂“singleton_product”创建 n 个产品。所有这些产品都将具有相同的平台(即平台“FooBar”)。
您仍然可以使用标准产品工厂“产品”来创建平台为“测试平台”的产品,但是当您调用它来创建第二个产品时,它将失败(如果平台名称设置为唯一)。
Not sure if this could be useful to you.
With this setup you can create n products using the factory 'singleton_product'. All those products will have same platform (i.e. platform 'FooBar').
You can still use the standard product factory 'product' to create a product with platform 'Test Platform', but it will fail when you call it to create the 2nd product (if platform name is set to be unique).