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

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

Overview

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

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

Constant Summary collapse

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

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



51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/rspec/multiple_subjects.rb', line 51

def autocorrect(node)
  return unless node.method_name.equal?(:subject) # Ignore `subject!`

  if named_subject?(node)
    rename_autocorrect(node)
  else
    remove_autocorrect(node)
  end
end

#on_block(node) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/rspec/multiple_subjects.rb', line 41

def on_block(node)
  return unless example_group?(node)

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

  subjects[0...-1].each do |subject|
    add_offense(subject, location: :expression)
  end
end