Class: RuboCop::Cop::RSpec::ImplicitExpect

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rspec/implicit_expect.rb

Overview

Check that a consistent implicit expectation style is used.

This cop can be configured using the ‘EnforcedStyle` option and supports the `–auto-gen-config` flag.

Examples:

‘EnforcedStyle: is_expected` (default)

# bad
it { should be_truthy }

# good
it { is_expected.to be_truthy }

‘EnforcedStyle: should`

# bad
it { is_expected.to be_truthy }

# good
it { should be_truthy }

Constant Summary collapse

MSG =
'Prefer `%<good>s` over `%<bad>s`.'
RESTRICT_ON_SEND =
Runners.all + %i[should should_not]
ENFORCED_REPLACEMENTS =
alternatives.merge(alternatives.invert).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

#implicit_expect(node) ⇒ Object



34
35
36
37
38
39
# File 'lib/rubocop/cop/rspec/implicit_expect.rb', line 34

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

#on_send(node) ⇒ Object

rubocop:disable Metrics/MethodLength



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rubocop/cop/rspec/implicit_expect.rb', line 49

def on_send(node) # rubocop:disable Metrics/MethodLength
  return unless (source_range = offending_expect(node))

  expectation_source = source_range.source

  if expectation_source.start_with?(style.to_s)
    correct_style_detected
  else
    opposite_style_detected

    msg = offense_message(expectation_source)
    add_offense(source_range, message: msg) do |corrector|
      replacement = replacement_source(expectation_source)
      corrector.replace(source_range, replacement)
    end
  end
end