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_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

#implicit_expect(node) ⇒ Object


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

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

#lambda?(node) ⇒ Object


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

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

#lambda_subject?(node) ⇒ Object


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

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

#on_send(node) ⇒ Object


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

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