Skip to content

Instantly share code, notes, and snippets.

@alexcameron89
Created March 11, 2019 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexcameron89/401fd48d0f21fcf7262c4d20422efee5 to your computer and use it in GitHub Desktop.
Save alexcameron89/401fd48d0f21fcf7262c4d20422efee5 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", github: "rails/rails"
gem "mysql2"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "mysql2", database: "rails")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
end
create_table :comments, force: true do |t|
t.integer :post_id
end
add_index :comments, :post_id, unique: true
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class BugTest < Minitest::Test
# PROBLEM
# When create fails, the autoincremented id does not roll back
def test_primary_key_growth
post_one = Post.create!
comment_for_post_one = Comment.create_or_find_by(post: post_one)
# Create fails for Post 1's second comment and it finds the same record for
# first_comment_for_post_one
1000.times do
second_comment_for_post_one = Comment.create_or_find_by(post: post_one)
assert_equal second_comment_for_post_one, comment_for_post_one
end
post_two = Post.create!
# This fails
# Failure:
# BugTest#test_primary_key_growth [create_or_find_by.rb:56]:
# Expected: 2
# Actual: #<Comment id: 1002, post_id: 2>
comment_for_post_two = Comment.create_or_find_by(post: post_two)
assert_equal comment_for_post_one.id + 1, comment_for_post_two.id
end
# This is nothing new, as the same thing can happen with `create`
def test_create
post_one = Post.create!
comment_for_post_one = Comment.create(post: post_one)
1000.times do
assert_raises ActiveRecord::RecordNotUnique do
second_comment_for_post_one = Comment.create(post: post_one)
end
end
post_two = Post.create!
comment_for_post_two = Comment.create(post: post_two)
assert_equal comment_for_post_one.id + 1, comment_for_post_two.id
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment