Class: RuboCop::Cop::RSpec::ExampleWording

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

Overview

Checks for common mistakes in example descriptions.

This cop will correct docstrings that begin with ‘should’ and ‘it’. This cop will also look for insufficient examples and call them out.

Use the DisallowedExamples setting to prevent unclear or insufficient descriptions. Please note that this config will not be treated as case sensitive.

Examples:

# bad
it 'should find nothing' do
end

it 'will find nothing' do
end

# good
it 'finds nothing' do
end
# bad
it 'it does things' do
end

# good
it 'does things' do
end

‘DisallowedExamples: [’works’]‘ (default)

# bad
it 'works' do
end

# good
it 'marks the task as done' do
end

See Also:

Constant Summary collapse

MSG_SHOULD =
'Do not use should when describing your tests.'
MSG_WILL =
'Do not use the future tense when describing your tests.'
MSG_IT =
"Do not repeat 'it' when describing your tests."
MSG_INSUFFICIENT_DESCRIPTION =
'Your example description is ' \
'insufficient.'
SHOULD_PREFIX =
/\Ashould(?:n't|n’t)?\b/i.freeze
WILL_PREFIX =
/\A(?:will|won't|won’t)\b/i.freeze
IT_PREFIX =
/\Ait /i.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

#it_description(node) ⇒ Object



74
75
76
77
78
79
# File 'lib/rubocop/cop/rspec/example_wording.rb', line 74

def_node_matcher :it_description, <<~PATTERN
  (block (send _ :it ${
    (str $_)
    (dstr (str $_ ) ...)
  } ...) ...)
PATTERN

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/rubocop/cop/rspec/example_wording.rb', line 81

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  it_description(node) do |description_node, message|
    if message.match?(SHOULD_PREFIX)
      add_wording_offense(description_node, MSG_SHOULD)
    elsif message.match?(WILL_PREFIX)
      add_wording_offense(description_node, MSG_WILL)
    elsif message.match?(IT_PREFIX)
      add_wording_offense(description_node, MSG_IT)
    elsif insufficient_docstring?(description_node)
      add_offense(docstring(description_node),
                  message: MSG_INSUFFICIENT_DESCRIPTION)
    end
  end
end