forked from curious725/rubocop-rspec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_wording.rb
66 lines (57 loc) · 1.63 KB
/
context_wording.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# `context` block descriptions should start with 'when', or 'with'.
#
# @see https://github.com/reachlocal/rspec-style-guide#context-descriptions
# @see http://www.betterspecs.org/#contexts
#
# @example `Prefixes` configuration option, defaults: 'when', 'with', and
# 'without'
# Prefixes:
# - when
# - with
# - without
# - if
#
# @example
# # bad
# context 'the display name not present' do
# # ...
# end
#
# # good
# context 'when the display name is not present' do
# # ...
# end
class ContextWording < Cop
MSG = 'Start context description with %<prefixes>s.'.freeze
def_node_matcher :context_wording, <<-PATTERN
(block (send #{RSPEC} { :context :shared_context } $(str #bad_prefix?) ...) ...)
PATTERN
def on_block(node)
context_wording(node) do |context|
add_offense(context, message: message)
end
end
private
def bad_prefix?(description)
!prefixes.include?(description.split.first)
end
def prefixes
cop_config['Prefixes'] || []
end
def message
format(MSG, prefixes: joined_prefixes)
end
def joined_prefixes
quoted = prefixes.map { |prefix| "'#{prefix}'" }
return quoted.first if quoted.size == 1
quoted << "or #{quoted.pop}"
quoted.join(', ')
end
end
end
end
end