class RuboCop::Cop::RSpec::HooksBeforeExamples

Checks for before/around/after hooks that come after an example.

@example

# Bad

it 'checks what foo does' do
  expect(foo).to be
end

before { prepare }
after { clean_up }

# Good
before { prepare }
after { clean_up }

it 'checks what foo does' do
  expect(foo).to be
end

Constants

MSG

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 45
def autocorrect(node)
  lambda do |corrector|
    first_example = find_first_example(node.parent)
    first_example_pos = first_example.loc.expression
    indent = "\n" + ' ' * first_example.loc.column

    corrector.insert_before(first_example_pos, source(node) + indent)
    corrector.remove(node_range_with_surrounding_space(node))
  end
end
on_block(node) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 39
def on_block(node)
  return unless example_group_with_body?(node)

  check_hooks(node.body) if multiline_block?(node.body)
end

Private Instance Methods

check_hooks(node) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 62
def check_hooks(node)
  first_example = find_first_example(node)
  return unless first_example

  node.each_child_node do |child|
    next if child.sibling_index < first_example.sibling_index
    next unless hook?(child)

    add_offense(
      child,
      message: format(MSG, hook: child.method_name)
    )
  end
end
find_first_example(node) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 77
def find_first_example(node)
  node.children.find { |sibling| example_or_group?(sibling) }
end
multiline_block?(block) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 58
def multiline_block?(block)
  block.begin_type?
end
node_range(node) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 90
def node_range(node)
  node.loc.expression.with(end_pos: final_end_location(node).end_pos)
end
node_range_with_surrounding_space(node) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 81
def node_range_with_surrounding_space(node)
  range = node_range(node)
  range_by_whole_lines(range, include_final_newline: true)
end
source(node) click to toggle source
# File lib/rubocop/cop/rspec/hooks_before_examples.rb, line 86
def source(node)
  node_range(node).source
end