Skip to content

Commit

Permalink
Merge pull request #1627 from rubocop/fix-indexed-let-false-positive-…
Browse files Browse the repository at this point in the history
…for-suffixes

Fix a false positive with suffixes after index-like numbers in RSpec/IndexedLet
  • Loading branch information
pirj authored Apr 19, 2023
2 parents 4014db8 + d7fbca9 commit 5a32e18
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
11 changes: 8 additions & 3 deletions lib/rubocop/cop/rspec/indexed_let.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/rspec/indexed_let_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 5a32e18

Please # to comment.