Class: RuboCop::Cop::Momocop::FactoryBotSingleFactoryPerDefine

Inherits:
Base
  • Object
show all
Includes:
Momocop::Helpers::FactoryBotHelper
Defined in:
lib/rubocop/cop/momocop/factory_bot_single_factory_per_define.rb

Overview

Ensures that each file contains only one top-level FactoryBot factory. Nested factories within a parent factory are allowed.

Examples:

# bad
FactoryBot.define do
  factory :user do
  end
end

FactoryBot.define do
  factory :profile do
  end
end

# good
FactoryBot.define do
  factory :user do
  end
end

# bad
FactoryBot.define do
  factory :user do
  end
end

FactoryBot.define do
  factory :admin_user, class: ‘User' do
  end
end

# good
FactoryBot.define do
  factory :user do
    factory :admin_user do
    end
  end
end

Constant Summary collapse

MSG =
'Only one top-level factory is allowed per FactoryBot.define.'
RESTRICT_ON_SEND =
%i[define].freeze

Constants included from Momocop::Helpers::FactoryBotHelper

Momocop::Helpers::FactoryBotHelper::RUBOCOP_HELPER_METHODS

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object

Define the investigation method to be called during cop processing.



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rubocop/cop/momocop/factory_bot_single_factory_per_define.rb', line 53

def on_send(node)
  return unless factory_bot_define?(node)

  factories = top_level_factories(node)

  return if factories.size <= 1

  # Register an offense for each factory beyond the first one.
  factories[1..].each do |factory|
    add_offense(factory.loc.expression, message: MSG)
  end
end