Created
May 7, 2019 13:40
-
-
Save Edouard-chin/dd06b11cf09523e430fddb4dc352bafa to your computer and use it in GitHub Desktop.
after_commit callback order not respected
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', ref: 'b1553fc45f' | |
gem "sqlite3" | |
gem "byebug" | |
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 :authors, force: true do |t| | |
t.integer :post_id | |
t.string :name | |
end | |
end | |
$NAME_CHANGES = [] | |
class Post < ActiveRecord::Base | |
has_one :author | |
before_create :create_default_author | |
after_commit :change_author_name | |
def create_default_author | |
build_author(name: 'John') | |
end | |
def change_author_name | |
author.update_name('Simon') | |
end | |
end | |
class Author < ActiveRecord::Base | |
belongs_to :post | |
after_commit :record | |
def update_name(name) | |
update!(name: name) | |
end | |
def record | |
$NAME_CHANGES << name | |
end | |
end | |
class BugTest < Minitest::Test | |
def test_something | |
Post.create! | |
assert_equal(['John', 'Simon'], $NAME_CHANGES) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment