#目次
①follow_redirectの意味.
②follow_redirectのイメージ.
③例文でfollow_redirectの挙動を確認.
#follow_redirectの意味.
一言で言うと⇨
「コントローラの中で記載されているリダイレクト先に従って」という意味。
#例文でfollow_redirectの挙動を確認
例 Usersコントローラの中に↓のようなアクションがあるとする.コントローラ内でしようとしていることは「ユーザー登録です」
ユーザー登録成功⇨@userにリダイレクト.
失敗⇨new.html.erbにリダイレクトするというコードです。
def create
@user = User.create(user_params)
if @user.save
flash[:success] = "登録おめでとう"
redirect_to @user
else
render "new"
end
end
ちゃんとユーザー登録が成功するかを確認するテストを書いてみる。
test "valid information" do
get signup_path
assert_difference 'User.count' do
post users_path , params: {user: {name: "umedamasanori", email: "user@yahoo.co.jp",password: "hogehoge", password_confirmation: "hogehoge"}}
end
follow_redirect!
assert_template "users/show"
end
end
↑での
follow_redirect!の役割は
「usersコントローラの中で記載されているリダイレクト先(redirect_to @user)にリダイレクトしてねということを明確にし、テスト環境の中で間違ったhtmlにリダイレクトするのを防ぐ」
間違ったhtmlにリダイレクトするのを防ぐとは?
⇨アクションの中にリダイレクト先が記載されていない場合デフォルトのhtmlが表示される
例
def index
end
⇨index.html.erbが表示される
しかしアクション内に別ページにリダイレクトするように指定した場合はデフォルトではなく指定されたhtmlが表示される
def index
redirect_to "new"
end
⇨ デフォルトのindex.html.erbではなくnew.html.erbが表示される
テストでfollow_redirect!を記載することによりデフォルトのhtmlではなく指定されたhtmlにリダイレクトするようにしている。要は間違ってデフォルトを表示しないようにしている。
その証拠に テストのfollow_redirect!をコメントにしてテストを走らせるとエラーになり
おそらく意味はデフォルトのhtmlを表示しようとしたがデフォルトのhtmlがなかったため<[]>空白になっていると思います。このことからfollow_redirect!がある事によってリダイレクト先を指定している。
Failure:
UsersSignupTest#test_valid_information [/home/ubuntu/environment/twitter/test/integration/users_signup_test.rb:23]:
expecting <"users/show"> but rendering with <[]>
```[f:id:masanakaniki:20230217132548p:plain]