Creating a Factory association that defaults to nil?
Asked Answered
I

2

7

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?

Induline answered 8/12, 2011 at 21:28 Comment(3)
Wouldn't it be nil by default if you do not mention this association in your factory definition at all?Housemaster
Good point. I was worried that doing that would mean using Factory in the seeds.rb file wouldn't work, but I believe now that worrying was incorrect.Induline
Check https://mcmap.net/q/1480724/-disabling-a-factorygirl-association-within-a-trait if you want to override association to nil.Sochi
F
0
Factory.define :user do |factory|
  factory.association :post
  factory.comment_id  nil
end
Far answered 8/12, 2011 at 21:33 Comment(0)
E
11

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.

Enter answered 17/1, 2016 at 9:18 Comment(1)
gosh, it'd be nice if FactoryBot would mention this in their docs, no?Top
F
0
Factory.define :user do |factory|
  factory.association :post
  factory.comment_id  nil
end
Far answered 8/12, 2011 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.