Class: RuboCop::Cop::Mable::HardcodedDatabaseFactoryBotId

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/mable/hardcoded_database_factory_bot_id.rb

Overview

Hardcoding factory bot Database IDs can cause race conditions if there are database unique constraints on the column

Examples:

# bad
Factoybot.create(:user, id: 1000)

expect(user.id).to eq 1000

# bad
create(:user, id: 1000)

expect(user.id).to eq 1000

# good
Factoybot.create(:user)

expect(user.id).to eq user.id

# good
create(:user)
let(:user_id) { user.id }

expect(user.id).to eq user_id

Constant Summary collapse

MSG =
'Avoid hardcoding Factory Bot database IDs, instead, let the factory set the ID and test the result'
RESTRICT_ON_SEND =
i[
  create
  create_list
  create_pair
  generate
  generate_list
].to_set.freeze

Instance Method Summary collapse

Instance Method Details

#hardcoded_factory_bot_primary_key?(node) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/mable/hardcoded_database_factory_bot_id.rb', line 46

def_node_matcher :hardcoded_factory_bot_primary_key?, "(send { _ | (const ... :FactoryBot) } _\n  (sym _)*\n  (hash\n    <(pair\n      (sym :id) (...)\n    ) pair ...>\n  )\n)\n"

#on_send(node) ⇒ Object



57
58
59
60
61
# File 'lib/rubocop/cop/mable/hardcoded_database_factory_bot_id.rb', line 57

def on_send(node)
  return unless hardcoded_factory_bot_primary_key?(node)

  add_offense(node)
end