Class: RuboCop::Cop::RSpec::LeadingSubject

Inherits:
Cop
  • Object
show all
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rspec/leading_subject.rb

Overview

Checks for ‘subject` definitions that come after `let` definitions.

Examples:

# bad
RSpec.describe User do
  let(:params) { blah }
  subject { described_class.new(params) }

  it 'is valid' do
    expect(subject.valid?).to be(true)
  end
end

# good
RSpec.describe User do
  subject { described_class.new(params) }

  let(:params) { blah }

  it 'is valid' do
    expect(subject.valid?).to be(true)
  end
end

Constant Summary collapse

MSG =
'Declare `subject` above any other `let` declarations.'.freeze

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/rubocop/cop/rspec/leading_subject.rb', line 46

def autocorrect(node)
  lambda do |corrector|
    first_let = find_first_let(node)
    first_let_position = first_let.loc.expression
    indent = "\n" + ' ' * first_let.loc.column
    corrector.insert_before(first_let_position, node.source + indent)
    corrector.remove(node_range(node))
  end
end

#on_block(node) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/rubocop/cop/rspec/leading_subject.rb', line 36

def on_block(node)
  return unless subject?(node) && !in_spec_block?(node)

  node.parent.each_child_node do |sibling|
    break if sibling.equal?(node)

    break add_offense(node, location: :expression) if let?(sibling)
  end
end