Skip to content

Commit

Permalink
Fix failse negatives for Rails/TransactionExitStatement
Browse files Browse the repository at this point in the history
  • Loading branch information
Tietew committed Mar 17, 2022
1 parent 7f709e2 commit 7327f97
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +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][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/rails/transaction_exit_statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def on_send(node)
return unless parent.block_type? && parent.body

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

statement = statement(statement_node)
message = format(MSG, statement: statement)
Expand All @@ -78,6 +78,10 @@ def statement(statement_node)
statement_node.method_name
end
end

def nested_block?(statement_node)
!statement_node.ancestors.find(&:block_type?).method?(:transaction)
end
end
end
end
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/rails/transaction_exit_statement_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,28 @@
RUBY
end

it 'registers an offense when `return` is used in `loop` in transactions' do
expect_offense(<<~RUBY)
ApplicationRecord.transaction do
loop do
return if condition
^^^^^^ Exit statement `return` is not allowed. Use `raise` (rollback) or `next` (commit).
end
end
RUBY
end

it 'registers an offense when `throw` is used in `loop` in transactions' do
expect_offense(<<~RUBY)
ApplicationRecord.transaction do
loop do
throw if condition
^^^^^ Exit statement `throw` is not allowed. Use `raise` (rollback) or `next` (commit).
end
end
RUBY
end

it 'does not register an offense when `break` is used in `loop` in transactions' do
expect_no_offenses(<<~RUBY)
ApplicationRecord.transaction do
Expand Down

0 comments on commit 7327f97

Please sign in to comment.