Skip to content

Improve user feedback if defining static association with a block #1503

@grekko

Description

@grekko

Problem this feature will solve

Given:

FactoryBot.define do
  user(factory: :author) { association(:author, role: role) }
end

DefinitionProxy#method_missing will declare the association and ignore any given block-argument.

Desired solution

DefinitionProxy#method_missing could warn users (this is just demo code :)):

def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondToMissing
  association_options = args.first

  if association_options.nil?
    __declare_attribute__(name, block)
  elsif __valid_association_options?(association_options)
    Kernel.puts 'warn: Dynamically provided attributes are ignored if `factory`-key is set.' if block
    association(name, association_options)
  else
    raise NoMethodError.new(<<~MSG)
      undefined method '#{name}' in '#{@definition.name}' factory
      Did you mean? '#{name} { #{association_options.inspect} }'
    MSG
  end
end

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions