Skip to content

Commit 7327f97

Browse files
committed
Fix failse negatives for Rails/TransactionExitStatement
1 parent 7f709e2 commit 7327f97

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#673](https://github.com/rubocop/rubocop-rails/pull/673): Fix a false negative for `Rails/TransactionExitStatement` when `return` or `throw` is used in a block in transactions. ([@Tietew][])

lib/rubocop/cop/rails/transaction_exit_statement.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def on_send(node)
5858
return unless parent.block_type? && parent.body
5959

6060
exit_statements(parent.body).each do |statement_node|
61-
next unless statement_node.ancestors.find(&:block_type?).method?(:transaction)
61+
next if statement_node.break_type? && nested_block?(statement_node)
6262

6363
statement = statement(statement_node)
6464
message = format(MSG, statement: statement)
@@ -78,6 +78,10 @@ def statement(statement_node)
7878
statement_node.method_name
7979
end
8080
end
81+
82+
def nested_block?(statement_node)
83+
!statement_node.ancestors.find(&:block_type?).method?(:transaction)
84+
end
8185
end
8286
end
8387
end

spec/rubocop/cop/rails/transaction_exit_statement_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,28 @@
4444
RUBY
4545
end
4646

47+
it 'registers an offense when `return` is used in `loop` in transactions' do
48+
expect_offense(<<~RUBY)
49+
ApplicationRecord.transaction do
50+
loop do
51+
return if condition
52+
^^^^^^ Exit statement `return` is not allowed. Use `raise` (rollback) or `next` (commit).
53+
end
54+
end
55+
RUBY
56+
end
57+
58+
it 'registers an offense when `throw` is used in `loop` in transactions' do
59+
expect_offense(<<~RUBY)
60+
ApplicationRecord.transaction do
61+
loop do
62+
throw if condition
63+
^^^^^ Exit statement `throw` is not allowed. Use `raise` (rollback) or `next` (commit).
64+
end
65+
end
66+
RUBY
67+
end
68+
4769
it 'does not register an offense when `break` is used in `loop` in transactions' do
4870
expect_no_offenses(<<~RUBY)
4971
ApplicationRecord.transaction do

0 commit comments

Comments
 (0)