Class: RuboCop::Cop::RSpec::MultipleSubjects

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rspec/multiple_subjects.rb

Overview

Checks if an example group defines ‘subject` multiple times.

This cop does not support autocorrection in some cases. The autocorrect behavior for this cop depends on the type of duplication:

- If multiple named subjects are defined then this probably indicates
  that the overwritten subjects (all subjects except the last
  definition) are effectively being used to define helpers. In this
  case they are replaced with `let`.

- If multiple unnamed subjects are defined though then this can *only*
  be dead code and we remove the overwritten subject definitions.

- If subjects are defined with `subject!` then we don't autocorrect.
  This is enough of an edge case that people can just move this to
  a `before` hook on their own

Examples:

# bad
describe Foo do
  subject(:user) { User.new }
  subject(:post) { Post.new }
end

# good
describe Foo do
  let(:user) { User.new }
  subject(:post) { Post.new }
end

# bad (does not support autocorrection)
describe Foo do
  subject!(:user) { User.new }
  subject!(:post) { Post.new }
end

# good
describe Foo do
  before do
    User.new
    Post.new
  end
end

Constant Summary collapse

MSG =
'Do not set more than one subject per example group'

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

Methods included from RSpec::Language

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

Instance Method Details

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



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

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless example_group?(node)

  subjects = RuboCop::RSpec::ExampleGroup.new(node).subjects

  subjects[0...-1].each do |subject|
    add_offense(subject) do |corrector|
      autocorrect(corrector, subject)
    end
  end
end