Skip to content

Instantly share code, notes, and snippets.

@alexcameron89
Created March 8, 2019 19:05
Show Gist options
  • Save alexcameron89/c6f83b83f9cc53176aef41f89a882d92 to your computer and use it in GitHub Desktop.
Save alexcameron89/c6f83b83f9cc53176aef41f89a882d92 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 "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
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
# 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