FactoryGirl - Overriding a parent association

I've been working a lot in RSpec and with FactoryGirl recently and came across a need to change the way a factory worked. This is in existing code and I didn't want to go through the whole codebase and see where the factory was defined and do things differently. I wanted to override the existing behavior for just one test that I needed to run.

Suppose you have a factory that looks like:

factory :notification do
  association :sender, :factory => :sending_account
  association :receiver, :factory => :receiving_account
end

and I want another factory where I want to use the parent notification, but just not have a receiver. It's as simple as:

factory :notification_without_receiver, parent: :notification do
  receiver nil
end

I was trying all kinds of things and the simplest answer was the correct one. Thanks thoughtbot for a wonderful gem!

Share this post