Class: RuboCop::Cop::RSpec::ImplicitBlockExpectation

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

Overview

Check that implicit block expectation syntax is not used.

Prefer using explicit block expectations.

Examples:

# bad
subject { -> { do_something } }
it { is_expected.to change(something).to(new_value) }

# good
it 'changes something to a new value' do
  expect { do_something }.to change(something).to(new_value)
end

Constant Summary collapse

MSG =
'Avoid implicit block expectations.'
RESTRICT_ON_SEND =
%i[is_expected should should_not].freeze

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

#implicit_expect(node) ⇒ Object



36
37
38
# File 'lib/rubocop/cop/rspec/implicit_block_expectation.rb', line 36

def_node_matcher :implicit_expect, <<~PATTERN
  $(send nil? {:is_expected :should :should_not} ...)
PATTERN

#lambda?(node) ⇒ Object



25
26
27
28
29
30
# File 'lib/rubocop/cop/rspec/implicit_block_expectation.rb', line 25

def_node_matcher :lambda?, <<~PATTERN
  {
    (send (const nil? :Proc) :new)
    (send nil? {:proc :lambda})
  }
PATTERN

#lambda_subject?(node) ⇒ Object



33
# File 'lib/rubocop/cop/rspec/implicit_block_expectation.rb', line 33

def_node_matcher :lambda_subject?, '(block #lambda? ...)'

#on_send(node) ⇒ Object



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

def on_send(node)
  implicit_expect(node) do |implicit_expect|
    subject = nearest_subject(implicit_expect)
    add_offense(implicit_expect) if lambda_subject?(subject&.body)
  end
end