class FactoryBot::Linter

Attributes

factories_to_lint[R]
factory_strategy[R]
invalid_factories[R]

Public Class Methods

new(factories, strategy: :create, traits: false, verbose: false) click to toggle source
# File lib/factory_bot/linter.rb, line 3
def initialize(factories, strategy: :create, traits: false, verbose: false)
  @factories_to_lint = factories
  @factory_strategy = strategy
  @traits = traits
  @verbose = verbose
  @invalid_factories = calculate_invalid_factories
end

Public Instance Methods

lint!() click to toggle source
# File lib/factory_bot/linter.rb, line 11
def lint!
  if invalid_factories.any?
    raise InvalidFactoryError, error_message
  end
end

Private Instance Methods

calculate_invalid_factories() click to toggle source
# File lib/factory_bot/linter.rb, line 21
def calculate_invalid_factories
  factories_to_lint.each_with_object(Hash.new([])) do |factory, result|
    errors = lint(factory)
    result[factory] |= errors unless errors.empty?
  end
end
error_message() click to toggle source
# File lib/factory_bot/linter.rb, line 90
    def error_message
      lines = invalid_factories.map { |_factory, exceptions|
        exceptions.map(&error_message_type)
      }.flatten

      <<~ERROR_MESSAGE.strip
        The following factories are invalid:

        #{lines.join("\n")}
      ERROR_MESSAGE
    end
error_message_type() click to toggle source
# File lib/factory_bot/linter.rb, line 102
def error_message_type
  if @verbose
    :verbose_message
  else
    :message
  end
end
lint(factory) click to toggle source
# File lib/factory_bot/linter.rb, line 62
def lint(factory)
  if @traits
    lint_factory(factory) + lint_traits(factory)
  else
    lint_factory(factory)
  end
end
lint_factory(factory) click to toggle source
# File lib/factory_bot/linter.rb, line 70
def lint_factory(factory)
  result = []
  begin
    FactoryBot.public_send(factory_strategy, factory.name)
  rescue => e
    result |= [FactoryError.new(e, factory)]
  end
  result
end
lint_traits(factory) click to toggle source
# File lib/factory_bot/linter.rb, line 80
def lint_traits(factory)
  result = []
  factory.definition.defined_traits.map(&:name).each do |trait_name|
    FactoryBot.public_send(factory_strategy, factory.name, trait_name)
  rescue => e
    result |= [FactoryTraitError.new(e, factory, trait_name)]
  end
  result
end