class RuboCop::Cop::RSpec::LetBeforeExamples

Checks for ‘let` definitions that come after an example.

@example

# bad
let(:foo) { bar }

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

let(:some) { other }

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

# good
let(:foo) { bar }
let(:some) { other }

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

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

Constants

MSG

Public Class Methods

autocorrect_incompatible_with() click to toggle source
# File lib/rubocop/cop/rspec/let_before_examples.rb, line 54
def self.autocorrect_incompatible_with
  [RSpec::ScatteredLet]
end

Public Instance Methods

on_block(node) click to toggle source
# File lib/rubocop/cop/rspec/let_before_examples.rb, line 58
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless example_group_with_body?(node)

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

Private Instance Methods

autocorrect(corrector, node, first_example) click to toggle source
# File lib/rubocop/cop/rspec/let_before_examples.rb, line 93
def autocorrect(corrector, node, first_example)
  RuboCop::RSpec::Corrector::MoveNode.new(
    node, corrector, processed_source
  ).move_before(first_example)
end
check_let_declarations(node) click to toggle source
# File lib/rubocop/cop/rspec/let_before_examples.rb, line 74
def check_let_declarations(node)
  first_example = find_first_example(node)
  return unless first_example

  correct = !example_group_with_include_examples?(node)

  first_example.right_siblings.each do |sibling|
    next unless let?(sibling)

    add_offense(sibling) do |corrector|
      autocorrect(corrector, sibling, first_example) if correct
    end
  end
end
example_group_with_include_examples?(body) click to toggle source
# File lib/rubocop/cop/rspec/let_before_examples.rb, line 66
def example_group_with_include_examples?(body)
  body.children.any? { |sibling| include_examples?(sibling) }
end
find_first_example(node) click to toggle source
# File lib/rubocop/cop/rspec/let_before_examples.rb, line 89
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/let_before_examples.rb, line 70
def multiline_block?(block)
  block.begin_type?
end