Class: RuboCop::Cop::Infinum::FactoryBotAssociation

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
IgnoredNode
Defined in:
lib/rubocop/cop/infinum/factory_bot_association.rb

Overview

This cop looks for ‘association’ in factories that specify a ‘:factory’ option and tells you to use explicit build reference which improves the performance as cascading factories will not be saved unless needed to

Examples:

#bad
 FactoryBot.define do
   factory :book do
     title { 'Lord of the Rings' }
     association :author
   end
 end

 FactoryBoy.define do
   factory :book do
     title {'Lord of the Rings'}
     author { association :author }
   end
 end

 #good
 FactoryBot.define do
   factory :book do
     title { 'Lord of the Rings' }
     author { build(:author) }
   end
 end

 FactoryBot.define do
   factory :author do
     name { 'J. R. R. Tolkien' }
   end
 end

Constant Summary collapse

MSG =
'Use %<association_name>s { build(:%<factory_name>s) } instead'

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/rubocop/cop/infinum/factory_bot_association.rb', line 55

def on_block(node)
  inline_association_definition(node) do |association_name, factory_name|
    message = format(MSG, association_name: association_name.to_s, factory_name: factory_name.to_s)

    handle_offense(node, message)
  end
end

#on_send(node) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'lib/rubocop/cop/infinum/factory_bot_association.rb', line 63

def on_send(node)
  association_definition(node) do |association_name, factory_name|
    factory_name = [association_name] if factory_name.empty?

    message = format(MSG, association_name: association_name.to_s, factory_name: factory_name.first.to_s)

    handle_offense(node, message)
  end
end