Skip to content

Commit

Permalink
Refactor RSpec/ContextWording cop to use allowed? method for patter…
Browse files Browse the repository at this point in the history
…n validation
  • Loading branch information
ydah committed Oct 18, 2024
1 parent 961e544 commit c3947f4
Showing 1 changed file with 9 additions and 15 deletions.
24 changes: 9 additions & 15 deletions lib/rubocop/cop/rspec/context_wording.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,17 @@ class ContextWording < Base
(block (send #rspec? { :context :shared_context } $({str dstr xstr} ...) ...) ...)
PATTERN

# @!method allowed?(node)
def_node_matcher :allowed?, <<~PATTERN
{
(str #matches_allowed_pattern?)
(xstr (str #matches_allowed_pattern?) ...)
}
PATTERN

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
context_wording(node) do |context|
if bad_pattern?(context)
unless allowed?(context)
message = format(MSG, patterns: expect_patterns)
add_offense(context, message: message)
end
Expand All @@ -84,20 +92,6 @@ def prefix_regexes
@prefix_regexes ||= prefixes.map { |pre| /^#{Regexp.escape(pre)}\b/ }
end

def bad_pattern?(node)
return false if allowed_patterns.empty?

!matches_allowed_pattern?(description(node))
end

def description(context)
if context.xstr_type?
context.value.value
else
context.value
end
end

def expect_patterns
inspected = allowed_patterns.map do |pattern|
pattern.inspect.gsub(/\A"|"\z/, '/')
Expand Down

0 comments on commit c3947f4

Please sign in to comment.