Class: RuboCop::Cop::RSpec::LetBeforeExamples

Inherits:
Cop
  • Object
show all
Includes:
RangeHelp, RSpec::FinalEndLocation
Defined in:
lib/rubocop/cop/rspec/let_before_examples.rb

Overview

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

Examples:

# 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

Constant Summary collapse

MSG =
'Move `let` before the examples in the group.'

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL, RSpec::Language::RSPEC

Instance Method Summary collapse

Methods included from RSpec::FinalEndLocation

#final_end_location

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/rubocop/cop/rspec/let_before_examples.rb', line 52

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) ⇒ Object



46
47
48
49
50
# File 'lib/rubocop/cop/rspec/let_before_examples.rb', line 46

def on_block(node)
  return unless example_group_with_body?(node)

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