访问*其他*工厂中的factory_girl工厂
我在 Rails 应用程序中使用 factory_girl 插件。对于每个模型,我都有一个相应的 ruby 文件,其中包含工厂数据,例如
Factory.define :valid_thing, :class => Thing do |t|
t.name 'Some valid thing'
# t.user ???
end
我有很多不同类型的用户(已在用户工厂中定义)。如果我尝试以下操作:
Factory.define :valid_thing, :class => Thing do |t|
t.name 'Some valid thing'
t.user Factory(:valid_user) # Fails
end
我收到以下错误:
# No such factory: valid_user (ArgumentError)
:valid_user 实际上是有效的 - 我可以在我的测试中使用它 - 只是不在我的工厂中。有什么方法可以使用这里另一个文件中定义的工厂吗?
I'm using the factory_girl plugin in my rails application. For each model, I have a corresponding ruby file containing the factory data e.g.
Factory.define :valid_thing, :class => Thing do |t|
t.name 'Some valid thing'
# t.user ???
end
I have lots of different types of users (already defined in the user factory). If I try the following though:
Factory.define :valid_thing, :class => Thing do |t|
t.name 'Some valid thing'
t.user Factory(:valid_user) # Fails
end
I get the following error:
# No such factory: valid_user (ArgumentError)
The :valid_user is actually valid though - I can use it in my tests - just not in my factories. Is there any way I can use a factory defined in another file in here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用以下代码:
将调用包装在 {} 中会导致 Factory Girl 在创建 :valid_thing 工厂之前不会评估大括号内的代码。这将迫使它等待 :valid_user 工厂加载(您的示例失败,因为它尚未加载),它还会导致为每个 :valid_thing 创建一个新的 :valid_user 而不是为所有 :valid_thing 创建相同的用户:valid_thing's(这可能就是您想要的)。
You should use this code:
Wrapping the call in {} causes Factory Girl to not evaluate the code inside of the braces until the :valid_thing factory is created. This will force it to wait until the :valid_user factory has been loaded (Your example is failing because it is not yet loaded), it will also cause a new :valid_user to be created for each :valid_thing rather than having the same user for all :valid_thing's (Which is probably what you want).
尝试使用关联方法,例如:
Try using the association method like:
从问题的年龄来看,这可能是 Factory Girl 的一个新功能,但如果工厂中的属性名称与工厂的名称相同,则只需调用工厂中的属性名称即可将其填充为关联工厂一代。
这应该会导致用户字段查找具有相同名称的工厂并从中填充它。
Potentially a new feature to Factory Girl judging by the age of the question, but if the name of your attribute in the Factory is the same as the name of the factory, simply calling the name of the attribute in your factory will populate it with the associated Factory generation.
This should result in the user field looking for a factory with the same name and populating it from that.