Class: RuboCop::Cop::RSpec::RepeatedSubjectCall

Inherits:
Base
  • Object
show all
Includes:
TopLevelGroup
Defined in:
lib/rubocop/cop/rspec/repeated_subject_call.rb

Overview

Checks for repeated calls to subject missing that it is memoized.

Examples:

# bad
it do
  subject
  expect { subject }.to not_change { A.count }
end

it do
  expect { subject }.to change { A.count }
  expect { subject }.to not_change { A.count }
end

# good
it do
  expect { my_method }.to change { A.count }
  expect { my_method }.to not_change { A.count }
end

# also good
it do
  expect { subject.a }.to change { A.count }
  expect { subject.b }.to not_change { A.count }
end

Constant Summary collapse

MSG =
'Calls to subject are memoized, this block is misleading'

Instance Method Summary collapse

Methods included from TopLevelGroup

#on_new_investigation, #top_level_groups

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?

Instance Method Details

#on_top_level_group(node) ⇒ Object



65
66
67
68
69
# File 'lib/rubocop/cop/rspec/repeated_subject_call.rb', line 65

def on_top_level_group(node)
  @subjects_by_node = detect_subjects_in_scope(node)

  detect_offenses_in_block(node)
end

#subject?(node) {|Symbol| ... } ⇒ Object

Find a named or unnamed subject definition

Examples:

anonymous subject

subject?(parse('subject { foo }').ast) do |name|
  name # => :subject
end

named subject

subject?(parse('subject(:thing) { foo }').ast) do |name|
  name # => :thing
end

Parameters:

  • node (RuboCop::AST::Node)

Yields:

  • (Symbol)

    subject name



53
54
55
56
57
58
# File 'lib/rubocop/cop/rspec/repeated_subject_call.rb', line 53

def_node_matcher :subject?, <<-PATTERN
  (block
    (send nil?
      { #Subjects.all (sym $_) | $#Subjects.all }
    ) args ...)
PATTERN

#subject_calls(node, method_name) ⇒ Object



61
62
63
# File 'lib/rubocop/cop/rspec/repeated_subject_call.rb', line 61

def_node_search :subject_calls, <<~PATTERN
  (send nil? %)
PATTERN