Class: RuboCop::Cop::Minitest::LifecycleHooksOrder

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp, RuboCop::Cop::MinitestExplorationHelpers
Defined in:
lib/rubocop/cop/minitest/lifecycle_hooks_order.rb

Overview

Checks that lifecycle hooks are declared in the order in which they will be executed.

Examples:

# bad
class FooTest < Minitest::Test
  def teardown; end
  def setup; end
end

# good
class FooTest < Minitest::Test
  def setup; end
  def teardown; end
end

# bad (after test cases)
class FooTest < Minitest::Test
  def test_something
    assert foo
  end
  def setup; end
  def teardown; end
end

# good
class FooTest < Minitest::Test
  def setup; end
  def teardown; end
  def test_something
    assert foo
  end
end

# good (after non test case methods)
class FooTest < Minitest::Test
  def do_something; end
  def setup; end
  def teardown; end
end

Constant Summary collapse

MSG =
'`%<current>s` is supposed to appear before `%<previous>s`.'
REGULAR_METHOD_POSITION =

Regular method’s position should be last.

LIFECYCLE_HOOK_METHODS_IN_ORDER.size + 1
HOOKS_ORDER_MAP =
Hash.new do |hash, hook|
  hash[hook] = LIFECYCLE_HOOK_METHODS_IN_ORDER.index(hook) || REGULAR_METHOD_POSITION
end

Constants included from RuboCop::Cop::MinitestExplorationHelpers

RuboCop::Cop::MinitestExplorationHelpers::ASSERTION_PREFIXES, RuboCop::Cop::MinitestExplorationHelpers::LIFECYCLE_HOOK_METHODS, RuboCop::Cop::MinitestExplorationHelpers::LIFECYCLE_HOOK_METHODS_IN_ORDER

Instance Method Summary collapse

Instance Method Details

#on_class(class_node) ⇒ Object

rubocop:disable Metrics/MethodLength



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rubocop/cop/minitest/lifecycle_hooks_order.rb', line 60

def on_class(class_node)
  return unless test_class?(class_node)

  previous_index = -1
  previous_hook_node = nil

  hooks_and_test_cases(class_node).each do |node|
    hook = node.method_name
    index = HOOKS_ORDER_MAP[hook]

    if index < previous_index
      message = format(MSG, current: hook, previous: previous_hook_node.method_name)
      add_offense(node, message: message) do |corrector|
        autocorrect(corrector, previous_hook_node, node)
      end
    end
    previous_index = index
    previous_hook_node = node
  end
end