Class: RuboCop::Cop::RSpec::ContextWording

Inherits:
Base
  • Object
show all
Includes:
AllowedPattern
Defined in:
lib/rubocop/cop/rspec/context_wording.rb

Overview

Checks that ‘context` docstring starts with an allowed prefix.

The default list of prefixes is minimal. Users are encouraged to tailor the configuration to meet project needs. Other acceptable prefixes may include ‘if`, `unless`, `for`, `before`, `after`, or `during`. They may consist of multiple words if desired.

If both ‘Prefixes` and `AllowedPatterns` are empty, this cop will always report an offense. So you need to set at least one of them.

This cop can be customized allowed context description pattern with ‘AllowedPatterns`. By default, there are no checking by pattern.

Examples:

‘Prefixes` configuration

# .rubocop.yml
# RSpec/ContextWording:
#   Prefixes:
#     - when
#     - with
#     - without
#     - if
#     - unless
#     - for
# bad
context 'the display name not present' do
  # ...
end

# good
context 'when the display name is not present' do
  # ...
end

‘AllowedPatterns` configuration


# .rubocop.yml
# RSpec/ContextWording:
#   AllowedPatterns:
#     - とき$
# bad
context '条件を満たす' do
  # ...
end

# good
context '条件を満たすとき' do
  # ...
end

See Also:

Constant Summary collapse

MSG_MATCH =
'Context description should match %<patterns>s.'
MSG_ALWAYS =
'Current settings will always report an offense. Please ' \
'add allowed words to `Prefixes` or `AllowedPatterns`.'

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

#context_wording(node) ⇒ Object



69
70
71
# File 'lib/rubocop/cop/rspec/context_wording.rb', line 69

def_node_matcher :context_wording, <<~PATTERN
  (block (send #rspec? { :context :shared_context } $({str dstr xstr} ...) ...) ...)
PATTERN

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



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

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  context_wording(node) do |context|
    unless matches_allowed_pattern?(description(context))
      add_offense(context, message: message)
    end
  end
end