Created
March 8, 2019 22:26
-
-
Save alexcameron89/bdcc33ac7325357e1fa4506b3b77ae23 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 "pg" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: "postgresql", 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! | |
post_two = Post.create! | |
first_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, first_comment_for_post_one | |
end | |
# This fails | |
# Failure: | |
# BugTest#test_primary_key_growth [create_or_find_by.rb:56]: | |
# Expected: 2 | |
# Actual: #<Comment id: 3, post_id: 2> | |
first_comment_for_post_two = Comment.create_or_find_by(post: post_two) | |
assert_equal first_comment_for_post_one.id + 1, first_comment_for_post_two.id | |
end | |
def test_create | |
post_one = Post.create! | |
post_two = Post.create! | |
first_comment_for_post_one = Comment.create(post: post_one) | |
assert_raises ActiveRecord::RecordNotUnique do | |
second_comment_for_post_one = Comment.create(post: post_one) | |
end | |
first_comment_for_post_two = Comment.create(post: post_two) | |
assert_equal first_comment_for_post_one.id + 1, first_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