follow_redirect!って何をfollowしてるの?: Railsチュートリアル備忘録 - 7章


ユーザー登録作成時のテストを書いております

/sample_app/test/integration/users_signup_test.rb
require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest
.
.
.

  test "valid signup information" do
    get signup_path
    assert_difference 'User.count', 1 do
      post users_path, params: { user: { name:  "Example User",
                                         email: "[email protected]",
                                         password:              "password",
                                         password_confirmation: "password" } }
    end
    follow_redirect!
    assert_template 'users/show'
  end

follow_redirect!とはなんぞ!

このメソッドは、POSTリクエストを送信した結果を見て、指定されたリダイレクト先に移動するメソッドです。(Railsチュートリアル)

なんとなく挙動は想像できる

わからないこと

指定されたリダイレクト先ってなんぞ?

検証

このままテストを実行してみると
rails test > Green

post users_pathに対応するコントローラーの挙動を参照すると

/sample_app/app/controllers/users_controller.rb
.
.
.
  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

この中のredirect_to @user > redirect_to root_pathに変更してみると

rails test > Red

 FAIL["test_valid_signup_information", #<Minitest::Reporters::Suite:0x000055e3f2c61b10 @name="UsersSignupTest">, 1.4677946789997804]
 test_valid_signup_information#UsersSignupTest (1.47s)
        expecting <"users/show"> but rendering with <["static_pages/home", 
...

リダイレクト先が"static_pages/home"になってるよと

結論

follow_redirect!は、
"POSTリクエストを送信した結果を見て"、
つまり対応するコントローラ内で明示されたリダイレクトの挙動に従っているようだ