Class: RuboCop::Cop::RSpec::MissingExpectationTargetMethod

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

Overview

Checks if ‘.to`, `not_to` or `to_not` are used.

The RSpec::Expectations::ExpectationTarget must use ‘to`, `not_to` or `to_not` to run. Therefore, this cop checks if other methods are used.

Examples:

# bad
expect(something).kind_of? Foo
is_expected == 42
expect{something}.eq? BarError

# good
expect(something).to be_a Foo
is_expected.to eq 42
expect{something}.to raise_error BarError

Constant Summary collapse

MSG =
'Use `.to`, `.not_to` or `.to_not` to set an expectation.'
RESTRICT_ON_SEND =
%i[expect is_expected].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

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

#expect?(node) ⇒ Object



27
28
29
30
31
32
# File 'lib/rubocop/cop/rspec/missing_expectation_target_method.rb', line 27

def_node_matcher :expect?, <<~PATTERN
  {
    (send nil? :expect ...)
    (send nil? :is_expected)
  }
PATTERN

#expect_block?(node) ⇒ Object



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

def_node_matcher :expect_block?, <<~PATTERN
  (block #expect? (args) _body)
PATTERN

#expectation_without_runner?(node) ⇒ Object



40
41
42
# File 'lib/rubocop/cop/rspec/missing_expectation_target_method.rb', line 40

def_node_matcher :expectation_without_runner?, <<~PATTERN
  (send {#expect? #expect_block?} !#Runners.all ...)
PATTERN

#on_send(node) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/rubocop/cop/rspec/missing_expectation_target_method.rb', line 44

def on_send(node)
  node = node.parent if node.parent&.block_type?

  expectation_without_runner?(node.parent) do
    add_offense(node.parent.loc.selector)
  end
end