Skip to content

Commit

Permalink
Exception in a callback tx should stop other callbacks within same tx
Browse files Browse the repository at this point in the history
  • Loading branch information
kevink1103 committed Dec 9, 2024
1 parent 1f45a92 commit 38b1b99
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
6 changes: 4 additions & 2 deletions lib/after_commit_everywhere/wrap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ def trigger_transactional_callbacks?
true
end

def committed!(*)
@handlers[:after_commit]&.call
def committed!(should_run_callbacks: true)
if should_run_callbacks
@handlers[:after_commit]&.call
end
end

def rolledback!(*)
Expand Down
21 changes: 15 additions & 6 deletions spec/after_commit_everywhere_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@
end

context "within transaction" do
context 'when prepend is true' do
let(:handler_1) { spy("handler_1") }
let(:handler_2) { spy("handler_2") }
let(:handler_1) { spy("handler_1") }
let(:handler_2) { spy("handler_2") }

context 'when prepend is true' do
it 'executes prepended callback first' do
ActiveRecord::Base.transaction do
example_class.new.after_commit { handler_1.call }
Expand All @@ -54,9 +54,6 @@
end

context 'when prepend is not specified' do
let(:handler_1) { spy("handler_1") }
let(:handler_2) { spy("handler_2") }

it 'executes callbacks in the order they were defined' do
ActiveRecord::Base.transaction do
example_class.new.after_commit { handler_1.call }
Expand Down Expand Up @@ -99,6 +96,18 @@
expect(handler).to have_received(:call)
end
end

it 'propagates an error raised in one of multiple callbacks' do
expect do
ActiveRecord::Base.transaction do
example_class.new.after_commit { raise 'this should prevent other callbacks being executed' }
example_class.new.after_commit { handler_1.call }
example_class.new.after_commit { handler_2.call }
end
end.to raise_error('this should prevent other callbacks being executed')
expect(handler_1).not_to have_received(:call)
expect(handler_2).not_to have_received(:call)
end
end

context "without transaction" do
Expand Down

0 comments on commit 38b1b99

Please sign in to comment.