Created
March 11, 2019 20:52
-
-
Save alexcameron89/4da7d4be2a8380a74f9d0708cc66d275 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 "sqlite3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") | |
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) | |
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! | |
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