diff --git a/changelog/fix_a_false_positive_for_rails_action_controller_flash_before_render.md b/changelog/fix_a_false_positive_for_rails_action_controller_flash_before_render.md new file mode 100644 index 0000000000..6bcb5dc3bd --- /dev/null +++ b/changelog/fix_a_false_positive_for_rails_action_controller_flash_before_render.md @@ -0,0 +1 @@ +* [#1244](https://github.com/rubocop/rubocop-rails/issues/1244): Fix a false positive for `Rails/ActionControllerFlashBeforeRender` when returning `redirect_to`. ([@earlopain][]) diff --git a/lib/rubocop/cop/rails/action_controller_flash_before_render.rb b/lib/rubocop/cop/rails/action_controller_flash_before_render.rb index 390ef37482..806e92e455 100644 --- a/lib/rubocop/cop/rails/action_controller_flash_before_render.rb +++ b/lib/rubocop/cop/rails/action_controller_flash_before_render.rb @@ -99,6 +99,8 @@ def instance_method_or_block?(node) def use_redirect_to?(context) context.right_siblings.compact.any? do |sibling| + # Unwrap `return redirect_to :index` + sibling = sibling.children.first if sibling.return_type? && sibling.children.one? sibling.send_type? && sibling.method?(:redirect_to) end end diff --git a/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb b/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb index 4e1dd01a20..4704d07a29 100644 --- a/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb +++ b/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb @@ -312,4 +312,20 @@ def create RUBY end end + + context 'when using `flash` after `render` and returning `redirect_to` in condition block' do + it 'does not register an offense' do + expect_no_offenses(<<~RUBY) + class HomeController < ApplicationController + def create + if condition + flash[:alert] = "msg" + return redirect_to "https://www.example.com/" + end + render :index + end + end + RUBY + end + end end