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

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

Overview

Enforce that subject is the first definition in the test.

Examples:

# bad
  let(:params) { blah }
  subject { described_class.new(params) }

  before { do_something }
  subject { described_class.new(params) }

  it { expect_something }
  subject { described_class.new(params) }
  it { expect_something_else }

# good
  subject { described_class.new(params) }
  let(:params) { blah }

# good
  subject { described_class.new(params) }
  before { do_something }

# good
  subject { described_class.new(params) }
  it { expect_something }
  it { expect_something_else }

Constant Summary collapse

MSG =
'Declare `subject` above any other `%<offending>s` declarations.'

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 inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/rubocop/cop/rspec/leading_subject.rb', line 59

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

#check_previous_nodes(node) ⇒ Object



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

def check_previous_nodes(node)
  node.parent.each_child_node do |sibling|
    if offending?(sibling)
      add_offense(
        node,
        location: :expression,
        message: format(MSG, offending: sibling.method_name)
      )
    end

    break if offending?(sibling) || sibling.equal?(node)
  end
end

#on_block(node) ⇒ Object



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

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

  check_previous_nodes(node)
end