Skip to content

Instantly share code, notes, and snippets.

@s-mage
Last active June 27, 2017 17:40
Show Gist options
  • Save s-mage/20ebc5af616c340abade206f9d4670ca to your computer and use it in GitHub Desktop.
Save s-mage/20ebc5af616c340abade206f9d4670ca to your computer and use it in GitHub Desktop.
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 'activerecord', '5.1'
gem 'pry'
gem 'sqlite3'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# 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 :parents, force: true do |t|
t.string :name
end
create_table :children, force: true do |t|
t.string :name
t.integer :parent_id
end
end
class Parent < ActiveRecord::Base
has_one :child, :inverse_of => :parent, :autosave => true
@@foo = 0
after_validation :foo
def foo
@@foo += 1
end
end
class Child < ActiveRecord::Base
belongs_to :parent, :inverse_of => :child, :autosave => true
end
class BugTest < Minitest::Test
def setup
@parent = Parent.create!(name: 'P')
@child = Child.new(name: 'Hi!')
@child.parent = @parent
@child.save!
end
# The case below fail, because
# https://github.com/rails/rails/blob/v4.2.7.1/activerecord/lib/active_record/autosave_association.rb#L441
# there `record.changed_for_autosave?` is true through it's not changed.
# It's true because `child` is changed.
# Therefore child is being saved in the wrong place, then saved one more time
# where it should be saved and as a result we see that `child.previous_changes` is {}
def test_prev_changes
assert_equal [nil, "Hi!"], @child.previous_changes[:name]
end
# This case pass because of another thing
# https://github.com/rails/rails/blob/v4.2.7.1/activerecord/lib/active_record/autosave_association.rb#L432
# association there is nil. But if I put debugger there and eval `parent` manually it would work
# as the third case.
def test_prev_changes_pass
child2 = Child.create!(name: '2', parent_id: @parent.id)
assert_equal [nil, "2"], child2.previous_changes[:name]
end
# This also fail for the same reason as test_prev_changes
def test_prev_changes2
child3 = Child.create!(name: '3', parent: @parent)
assert_equal [nil, "3"], child3.previous_changes[:name]
end
# This case fails because of similar behaviour in different place
def test_after_validation
@parent.class.class_variable_set('@@foo', 0)
@parent.update!(name: 'pp')
assert_equal 1, @parent.class.class_variable_get('@@foo')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment