class RuboCop::Cop::RSpec::FactoryBot::DynamicAttributeDefinedStatically
closed_at { 1.day.from_now }
# good
closed_at 1.day.from_now
# bad
kind { [:active, :rejected].sample }
# good
kind [:active, :rejected].sample
# bad
@example
@see StaticAttributeDefinedDynamically
Prefer declaring dynamic attribute values in a block.
def autocorrect(node)
def autocorrect(node) if !method_uses_parens?(node.location) autocorrect_without_parens(node) elsif value_hash_without_braces?(node.descendants.first) autocorrect_hash_without_braces(node) else autocorrect_replacing_parens(node) end end
def autocorrect_hash_without_braces(node)
def autocorrect_hash_without_braces(node) autocorrect_replacing_parens(node, ' { { ', ' } }') end
def autocorrect_replacing_parens(node,
def autocorrect_replacing_parens(node, start_token = ' { ', end_token = ' }') lambda do |corrector| corrector.replace(node.location.begin, start_token) corrector.replace(node.location.end, end_token) end end
def autocorrect_without_parens(node)
def autocorrect_without_parens(node) lambda do |corrector| arguments = node.descendants.first expression = arguments.location.expression corrector.insert_before(expression, '{ ') corrector.insert_after(expression, ' }') end end
def method_uses_parens?(location)
def method_uses_parens?(location) return false unless location.begin && location.end location.begin.source == '(' && location.end.source == ')' end
def on_block(node)
def on_block(node) factory_attributes(node).to_a.flatten.each do |attribute| next if callback_with_symbol_proc?(attribute) || static?(attribute) add_offense(attribute, location: :expression) end end
def static?(attribute)
def static?(attribute) value_matcher(attribute).to_a.all? do |node| node.recursive_literal? || node.const_type? end end
def value_hash_without_braces?(node)
def value_hash_without_braces?(node) node.hash_type? && !node.braces? end