Creating a Factory association that defaults to nil?

久未见 提交于 2020-01-04 06:53:48

问题


Using the FactoryGirl gem, inside the factories.rb file, how can I create a factory with an association that defaults to nil?

I am thinking something along these lines:

Factory.define :user do |factory|
  factory.association :post
  factory.association :comment, :default => nil
end

Would that be right and would that be ok to do?


回答1:


Factory.define :user do |factory|
  factory.association :post
  factory.comment_id  nil
end



回答2:


FactoryGirl now benefits from a :null strategy. Therefore, you can define your association like this:

factory :user do
  association :post
  association :comment, strategy: :null
end

This will leave the association set to nil when using this factory. It's better to use this strategy than not defining the association altogether, because you can easily change strategies in traits/in the future.



来源:https://stackoverflow.com/questions/8437936/creating-a-factory-association-that-defaults-to-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!