Search code examples
ruby-on-railsrubyfactory-bot

Association used in default_value_for fails with FactoryBot


When using FactoryBot in conjunction of default_value_for gem, and when relying on an association that must be present like belongs_to to define the default value, I run in an error telling me that the relationship is not defined.

Here is a simplified example:

class Post < ApplicationRecord
  default_value_for(:author_email) { |p| p.account.owner_email }

  belongs_to :account
end
# in my tests
create(:post, account: account)

When running the test, I get

Failure/Error: default_value_for(:author_email) { |p| p.account.owner_email }

NoMethodError: undefined method `owner_email' for nil:NilClass

It works fine when I use it in the context of the controller, but fails within the test, how can I make sure account is defined?


Solution

  • Make sure to use initialize_with in your factory, so when assigning the attributes, your association is already defined.

    FactoryBot.define do
      factory :post do
        initialize_with { account.post.build(**attributes) }
    
        # insure there is always an account to build from
        association :account, factory: :account
      end
    end