class RuboCop::Cop::RSpec::ImplicitExpect

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.

@example ‘EnforcedStyle: is_expected` (default)

# bad
it { should be_truthy }

# good
it { is_expected.to be_truthy }

@example ‘EnforcedStyle: should`

# bad
it { is_expected.to be_truthy }

# good
it { should be_truthy }

Constants

ENFORCED_REPLACEMENTS
MSG
RESTRICT_ON_SEND

Public Instance Methods

on_send(node) click to toggle source
# 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

Private Instance Methods

is_expected_range(source_map) click to toggle source
# File lib/rubocop/cop/rspec/implicit_expect.rb, line 78
def is_expected_range(source_map) # rubocop:disable Naming/PredicateName
  Parser::Source::Range.new(
    source_map.expression.source_buffer,
    source_map.expression.begin_pos,
    source_map.selector.end_pos
  )
end
offending_expect(node) click to toggle source
# File lib/rubocop/cop/rspec/implicit_expect.rb, line 69
def offending_expect(node)
  case implicit_expect(node)
  when :is_expected
    is_expected_range(node.loc)
  when :should, :should_not
    node.loc.selector
  end
end
offense_message(offending_source) click to toggle source
# File lib/rubocop/cop/rspec/implicit_expect.rb, line 86
def offense_message(offending_source)
  format(
    MSG,
    good: replacement_source(offending_source),
    bad:  offending_source
  )
end
replacement_source(offending_source) click to toggle source
# File lib/rubocop/cop/rspec/implicit_expect.rb, line 94
def replacement_source(offending_source)
  ENFORCED_REPLACEMENTS.fetch(offending_source)
end