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

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
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.'

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Instance Method Details

#check_previous_nodes(node) ⇒ Object


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

def check_previous_nodes(node)
  offending_node(node) do |offender|
    msg = format(MSG, offending: offender.method_name)
    add_offense(node, message: msg) do |corrector|
      autocorrect(corrector, node, offender)
    end
  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