Module: RuboCop::Cop::FactoryBotUsage

Extended by:
NodePattern::Macros
Included in:
RuboCop::Cop::Flexport::EngineApiBoundary, RuboCop::Cop::Flexport::GlobalModelAccessFromEngine
Defined in:
lib/rubocop/cop/mixin/factory_bot_usage.rb

Overview

Helpers for detecting FactoryBot usage. rubocop:disable Metrics/ModuleLength

Defined Under Namespace

Classes: Factory

Constant Summary collapse

FACTORY_BOT_METHODS =
%i[
  attributes_for
  attributes_for_list
  build
  build_list
  build_pair
  build_stubbed
  build_stubbed_list
  create
  create_list
  create_pair
].freeze
@@factories =

Cache factories at the class level so that we don’t have to fetch them again for every file we lint. We use class variables here so that the cache can be shared by all cops that include this module. rubocop:disable Style/ClassVars

nil

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.factories_cacheObject



37
38
39
# File 'lib/rubocop/cop/mixin/factory_bot_usage.rb', line 37

def self.factories_cache
  @@factories
end

.factories_cache=(factories) ⇒ Object



41
42
43
# File 'lib/rubocop/cop/mixin/factory_bot_usage.rb', line 41

def self.factories_cache=(factories)
  @@factories = factories
end

Instance Method Details

#engines_pathObject

Raises:

  • (NotImplementedError)


73
74
75
# File 'lib/rubocop/cop/mixin/factory_bot_usage.rb', line 73

def engines_path
  raise NotImplementedError
end

#factory_filesObject



69
70
71
# File 'lib/rubocop/cop/mixin/factory_bot_usage.rb', line 69

def factory_files
  @factory_files ||= Dir['spec/factories/**/*.rb'] + Dir["#{engines_path}*/spec/factories/**/*.rb"]
end

#find_factoriesObject

Parses factory definition files, returning a hash mapping factory names to model class names for each file.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/mixin/factory_bot_usage.rb', line 52

def find_factories
  RuboCop::Cop::FactoryBotUsage.factories_cache ||= begin
    # We'll add factories here as we parse the factory files.
    @factories = {}

    # We'll add factories that specify a parent here, so we can resolve the
    # reference to the parent after we have finished parsing all the files.
    @parents = {}

    # Parse the factory files, then resolve any parent references.
    traverse_factory_files
    resolve_parents

    @factories
  end
end

#spec_file?Boolean

rubocop:enable Style/ClassVars

Returns:

  • (Boolean)


46
47
48
# File 'lib/rubocop/cop/mixin/factory_bot_usage.rb', line 46

def spec_file?
  processed_source&.path&.match?(/_spec\.rb$/) || false
end