class RuboCop::RSpec::Wording

RSpec example wording rewriter

Constants

ES_SUFFIX_PATTERN
IES_SUFFIX_PATTERN
SHOULDNT_BE_PREFIX
SHOULDNT_PREFIX
WILL_NOT_PREFIX
WONT_PREFIX

Attributes

ignores[R]

rubocop:enable Metrics/MethodLength

replacements[R]

rubocop:enable Metrics/MethodLength

text[R]

rubocop:enable Metrics/MethodLength

Public Class Methods

new(text, ignore:, replace:) click to toggle source
# File lib/rubocop/rspec/wording.rb, line 14
def initialize(text, ignore:, replace:)
  @text         = text
  @ignores      = ignore
  @replacements = replace
end

Public Instance Methods

rewrite() click to toggle source

rubocop:disable Metrics/MethodLength

# File lib/rubocop/rspec/wording.rb, line 21
def rewrite
  case text
  when SHOULDNT_BE_PREFIX
    replace_prefix(SHOULDNT_BE_PREFIX, 'is not')
  when SHOULDNT_PREFIX
    replace_prefix(SHOULDNT_PREFIX, 'does not')
  when WILL_NOT_PREFIX
    replace_prefix(WILL_NOT_PREFIX, 'does not')
  when WONT_PREFIX
    replace_prefix(WONT_PREFIX, 'does not')
  else
    remove_should_and_pluralize
  end
end

Private Instance Methods

append_suffix(word, suffix) click to toggle source
# File lib/rubocop/rspec/wording.rb, line 80
def append_suffix(word, suffix)
  suffix = suffix.upcase if uppercase?(word)

  "#{word}#{suffix}"
end
ignored_word?(word) click to toggle source
# File lib/rubocop/rspec/wording.rb, line 65
def ignored_word?(word)
  ignores.any? { |ignore| ignore.casecmp(word).zero? }
end
remove_should_and_pluralize() click to toggle source
# File lib/rubocop/rspec/wording.rb, line 51
def remove_should_and_pluralize
  _should, *words = text.split

  words.each_with_index do |word, index|
    next if ignored_word?(word)

    words[index] = substitute(word)

    break
  end

  words.join(' ')
end
replace_prefix(pattern, replacement) click to toggle source
# File lib/rubocop/rspec/wording.rb, line 41
def replace_prefix(pattern, replacement)
  text.sub(pattern) do |matched|
    uppercase?(matched) ? replacement.upcase : replacement
  end
end
substitute(word) click to toggle source
# File lib/rubocop/rspec/wording.rb, line 69
def substitute(word)
  # NOTE: Custom replacements are case sensitive.
  return replacements.fetch(word) if replacements.key?(word)

  case word
  when ES_SUFFIX_PATTERN  then append_suffix(word, 'es')
  when IES_SUFFIX_PATTERN then append_suffix(word[0..-2], 'ies')
  else append_suffix(word, 's')
  end
end
uppercase?(word) click to toggle source
# File lib/rubocop/rspec/wording.rb, line 47
def uppercase?(word)
  word.upcase.eql?(word)
end