class RuboCop::Cop::RSpec::IndexedLet
let(:item_2) { create(:item) }
let(:item_1) { create(:item) }
# good
@example ‘AllowedPatterns: [’item’]‘
let(:item_2) { create(:item) }
let(:item_1) { create(:item) }
# good
@example `AllowedIdentifiers: [’item_1’, ‘item_2’]‘
let(:item_2) { create(:item) }
let(:item_1) { create(:item) }
# good
let(:item_3) { create(:item) }
let(:item_2) { create(:item) }
let(:item_1) { create(:item) }
# bad
@example `Max: 2`
let(:invisible_item) { create(:item, visible: false) }
let(:visible_item) { create(:item, visible: true) }
# good
let(:item2) { create(:item) }
let(:item1) { create(:item) }
let(:item_2) { create(:item) }
let(:item_1) { create(:item) }
# bad
@example `Max: 1 (default)`
will also read those set in `Naming/VariableNumber`.
The configurable options `AllowedIdentifiers` and `AllowedPatterns`
is tested by this particular example.
It makes reading the test harder because it’s not clear what exactly
Do not set up test data using indexes (e.g., ‘item_1`, `item_2`).
def allowed_identifiers
def allowed_identifiers Array(config.for_cop('Naming/VariableNumber') .fetch('AllowedIdentifiers', [])) + Array(cop_config.fetch('AllowedIdentifiers', [])) end
def cop_config_patterns_values
def cop_config_patterns_values Array(config.for_cop('Naming/VariableNumber') .fetch('AllowedPatterns', [])) + Array(cop_config.fetch('AllowedPatterns', [])) end
def filter_indexed_lets(candidates)
def filter_indexed_lets(candidates) candidates .filter { |node| indexed_let?(node) } .group_by { |node| let_name_stripped_index(node) } .values .filter { |lets| lets.length > cop_config['Max'] } .flatten end
def indexed_let?(node)
def indexed_let?(node) let?(node) && SUFFIX_INDEX_REGEX.match?(let_name(node)) && !allowed_identifier?(let_name(node).to_s) && !matches_allowed_pattern?(let_name(node).to_s) end
def let_name_stripped_index(node)
def let_name_stripped_index(node) let_name(node).to_s.gsub(INDEX_REGEX, '') end
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler return unless spec_group?(node) children = node.body&.child_nodes return unless children filter_indexed_lets(children).each do |let_node| add_offense(let_node) end end