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

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

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#check_previous_nodes(node) ⇒ Object


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

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


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

def on_block(node)
  return unless subject?(node)
  return unless inside_example_group?(node)

  check_previous_nodes(node)
end