From d7fbca911a8844c2a07a3a918d355da508f92bb7 Mon Sep 17 00:00:00 2001 From: Phil Pirozhkov Date: Wed, 19 Apr 2023 00:36:40 +0300 Subject: [PATCH] Fix a false positive with suffixes after index-like numbers --- CHANGELOG.md | 2 ++ lib/rubocop/cop/rspec/indexed_let.rb | 11 ++++++++--- spec/rubocop/cop/rspec/indexed_let_spec.rb | 9 +++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d1650dff..f00a23299 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Master (Unreleased) +- Fix a false positive in `RSpec/IndexedLet` with suffixes after index-like numbers. ([@pirj]) + ## 2.20.0 (2023-04-18) - Add new `RSpec/IndexedLet` cop. ([@dmitrytsepelev]) diff --git a/lib/rubocop/cop/rspec/indexed_let.rb b/lib/rubocop/cop/rspec/indexed_let.rb index 91e8c2647..29717b3c7 100644 --- a/lib/rubocop/cop/rspec/indexed_let.rb +++ b/lib/rubocop/cop/rspec/indexed_let.rb @@ -56,19 +56,24 @@ def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler private - INDEX_REGEX = /_?\d+/.freeze + SUFFIX_INDEX_REGEX = /_?\d+$/.freeze + INDEX_REGEX = /\d+/.freeze def filter_indexed_lets(candidates) candidates .filter { |node| indexed_let?(node) } - .group_by { |node| let_name(node).to_s.gsub(INDEX_REGEX, '') } + .group_by { |node| let_name_stripped_index(node) } .values .filter { |lets| lets.length > cop_config['Max'] } .flatten end def indexed_let?(node) - let?(node) && INDEX_REGEX.match?(let_name(node)) + let?(node) && SUFFIX_INDEX_REGEX.match?(let_name(node)) + end + + def let_name_stripped_index(node) + let_name(node).to_s.gsub(INDEX_REGEX, '') end end end diff --git a/spec/rubocop/cop/rspec/indexed_let_spec.rb b/spec/rubocop/cop/rspec/indexed_let_spec.rb index fe2c9bf6f..5d1be103d 100644 --- a/spec/rubocop/cop/rspec/indexed_let_spec.rb +++ b/spec/rubocop/cop/rspec/indexed_let_spec.rb @@ -73,6 +73,15 @@ RUBY end + it 'ignores names with an index-like and a suffix' do + expect_no_offenses(<<~RUBY) + context SomeService do + let(:user_7_day_average) { 700 } + let(:user_30_day_average) { 3000 } + end + RUBY + end + it 'not flags which have different prefixes' do expect_no_offenses(<<~RUBY) describe SomeService do