Class: RuboCop::Cop::Discourse::FabricatorShorthand

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
IgnoredNode
Defined in:
lib/rubocop/cop/discourse/fabricator_shorthand.rb

Overview

When fabricating a record without custom attributes, we can use the fabricator shorthand as long as the identifier matches the fabricator name.

# bad fab!(:user) { Fabricate(:user) }

# good fab!(:user)

When the variable name doesn’t match the fabricator name but no custom attributes are used, we can use a more explicit syntax.

# bad fab!(:other_user) { Fabricate(:user) }

# good fab!(:other_user, :user)

When using custom attributes, the block form must be used.

# good fab!(:user) { Fabricate(:user, trust_level: TrustLevel) }

# good fab!(:other_user) { Fabricate(:user, trust_level: TrustLevel) }

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/rubocop/cop/discourse/fabricator_shorthand.rb', line 60

def on_block(node)
  same_name_fabricator?(node) do |expression, _identifier|
    add_offense(node, message: message_for_matching(expression.source)) do |corrector|
      next if part_of_ignored_node?(node)
      corrector.replace(node, expression.source)
    end
    ignore_node(node)
    return
  end

  different_name_fabricator?(node) do |expression, variable_name, fabricator_name|
    # Only apply when names don't match but there are no extra arguments
    next if variable_name == fabricator_name || has_extra_arguments?(node)

    add_offense(
      node,
      message: message_for_different_names(variable_name, fabricator_name),
    ) do |corrector|
      next if part_of_ignored_node?(node)
      corrector.replace(node, "fab!(:#{variable_name}, :#{fabricator_name})")
    end
    ignore_node(node)
  end
end