class RuboCop::Cop::RSpec::ExcessiveDocstringSpacing

Checks for excessive whitespace in example descriptions.

@example

# bad
it '  has  excessive   spacing  ' do
end

# good
it 'has excessive spacing' do
end

@example

# bad
context '  when a condition   is met  ' do
end

# good
context 'when a condition is met' do
end

Constants

MSG

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/rspec/excessive_docstring_spacing.rb, line 38
def on_send(node)
  example_description(node) do |description_node, message|
    return if description_node.heredoc?

    text = text(message)

    return unless excessive_whitespace?(text)

    add_whitespace_offense(description_node, text)
  end
end

Private Instance Methods

add_whitespace_offense(node, text) click to toggle source

@param node [RuboCop::AST::Node] @param text [String]

# File lib/rubocop/cop/rspec/excessive_docstring_spacing.rb, line 66
def add_whitespace_offense(node, text)
  docstring = docstring(node)
  corrected = strip_excessive_whitespace(text)

  add_offense(docstring) do |corrector|
    corrector.replace(docstring, corrected)
  end
end
docstring(node) click to toggle source
# File lib/rubocop/cop/rspec/excessive_docstring_spacing.rb, line 75
def docstring(node)
  expr = node.loc.expression

  Parser::Source::Range.new(
    expr.source_buffer,
    expr.begin_pos + 1,
    expr.end_pos - 1
  )
end
excessive_whitespace?(text) click to toggle source

@param text [String]

# File lib/rubocop/cop/rspec/excessive_docstring_spacing.rb, line 53
def excessive_whitespace?(text)
  return true if text.start_with?(' ') || text.end_with?(' ')

  text.match?(/[^\n ]  +[^ ]/)
end
strip_excessive_whitespace(text) click to toggle source

@param text [String]

# File lib/rubocop/cop/rspec/excessive_docstring_spacing.rb, line 60
def strip_excessive_whitespace(text)
  text.strip.gsub(/  +/, ' ')
end
text(node) click to toggle source

Recursive processing is required to process nested dstr nodes that is the case for -separated multiline strings with interpolation.

# File lib/rubocop/cop/rspec/excessive_docstring_spacing.rb, line 87
def text(node)
  case node.type
  when :dstr
    node.node_parts.map { |child_node| text(child_node) }.join
  when :str, :sym
    node.value
  when :begin
    node.source
  end
end