Skip to content

Commit 5a32e18

Browse files
authored
Merge pull request #1627 from rubocop/fix-indexed-let-false-positive-for-suffixes
Fix a false positive with suffixes after index-like numbers in RSpec/IndexedLet
2 parents 4014db8 + d7fbca9 commit 5a32e18

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Master (Unreleased)
44

5+
- Fix a false positive in `RSpec/IndexedLet` with suffixes after index-like numbers. ([@pirj])
6+
57
## 2.20.0 (2023-04-18)
68

79
- Add new `RSpec/IndexedLet` cop. ([@dmitrytsepelev])

lib/rubocop/cop/rspec/indexed_let.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,24 @@ def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
5656

5757
private
5858

59-
INDEX_REGEX = /_?\d+/.freeze
59+
SUFFIX_INDEX_REGEX = /_?\d+$/.freeze
60+
INDEX_REGEX = /\d+/.freeze
6061

6162
def filter_indexed_lets(candidates)
6263
candidates
6364
.filter { |node| indexed_let?(node) }
64-
.group_by { |node| let_name(node).to_s.gsub(INDEX_REGEX, '') }
65+
.group_by { |node| let_name_stripped_index(node) }
6566
.values
6667
.filter { |lets| lets.length > cop_config['Max'] }
6768
.flatten
6869
end
6970

7071
def indexed_let?(node)
71-
let?(node) && INDEX_REGEX.match?(let_name(node))
72+
let?(node) && SUFFIX_INDEX_REGEX.match?(let_name(node))
73+
end
74+
75+
def let_name_stripped_index(node)
76+
let_name(node).to_s.gsub(INDEX_REGEX, '')
7277
end
7378
end
7479
end

spec/rubocop/cop/rspec/indexed_let_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,15 @@
7373
RUBY
7474
end
7575

76+
it 'ignores names with an index-like and a suffix' do
77+
expect_no_offenses(<<~RUBY)
78+
context SomeService do
79+
let(:user_7_day_average) { 700 }
80+
let(:user_30_day_average) { 3000 }
81+
end
82+
RUBY
83+
end
84+
7685
it 'not flags which have different prefixes' do
7786
expect_no_offenses(<<~RUBY)
7887
describe SomeService do

0 commit comments

Comments
 (0)