Last active
January 26, 2016 15:50
-
-
Save domcleal/295f13e17886095d3ea7 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
begin | |
require 'bundler/inline' | |
rescue LoadError => e | |
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' | |
raise e | |
end | |
gemfile(true) do | |
source 'https://rubygems.org' | |
gem 'rails', github: 'rails/rails' | |
gem 'arel', github: 'rails/arel' | |
gem 'rack', github: 'rack/rack' | |
gem 'sprockets', github: 'rails/sprockets' | |
gem 'sprockets-rails', github: 'rails/sprockets-rails' | |
gem 'sass-rails', github: 'rails/sass-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| | |
t.integer :comments_count, :default => 0 | |
end | |
create_table :comments, force: true do |t| | |
t.integer :post_id | |
end | |
end | |
class Post < ActiveRecord::Base #domain | |
has_many :posts | |
end | |
class Comment < ActiveRecord::Base #hg | |
belongs_to :post, :counter_cache => :comments_count | |
end | |
class BugTest < Minitest::Test | |
def test_counter_update | |
post1, post2 = Post.create!, Post.create! | |
comment1 = Comment.create!(:post => post1) | |
puts "Created comment #{comment1.id} against post #{post1.id}" | |
assert_equal 1, post1.reload.comments_count | |
assert_equal 0, post2.reload.comments_count | |
puts "Asserted comment counters" | |
# Remove this finder to prevent a reload, which exposes the bug. Using the same | |
# newly created object prevents the counter being incremented again. | |
comment1 = Comment.find_by_id(comment1.id) | |
# The counter of both models are updated twice in this call instead of once. | |
# | |
# It's the model's association setter that's incrementing the counter, as well as | |
# a model callback monitoring post_id for changes. | |
comment1.update_attribute(:post, post2) | |
puts "Updated comment #{comment1.id} against post #{post2.id}" | |
assert_equal 0, post1.reload.comments_count | |
assert_equal 1, post2.reload.comments_count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment