ユーザー登録成功時の処理
ユーザー登録に成功すると、なぜかnewページに戻る。
これはcreateアクションでユーザーが作成されたあと、対応するcreateビューに行こうとするが、createビューが存在しないためである。
createビューは必要ないため、ここではユーザーのプロフィールページにリダイレクトすることにする。
  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to user_url(@user)
    else
      render 'new'
    end
  end
user_url(@user)の行き先は/user/:idへのGETリクエストであり、showアクションに到達する。
また、リダイレクトの場合名前付きルートは_pathではなく_urlを使用する。
なお、user_url(@user)を単に@userと書いてもよいらしい。
flash変数を使って、ユーザー登録成功時のメッセージを表示している。
ユーザー登録成功時のテスト
ユーザー登録成功時のテストを書く。
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: "user@example.com",
                                         password:              "password",
                                         password_confirmation: "password" } }
    end
    follow_redirect!
    assert_template 'users/show'
    assert_not flash.empty?
  end
end
ユーザー登録失敗時のテストと基本は同じ。
こちらはassert_differenceを使っている。
これはブロックの前後で第一引数が第二引数分だけ増減したことを確認する。
ユーザー登録の成功により、User.countは1増えているはずである。
リダイレクト先に移動するにはfollow_redirect!を使う。
flashが表示されていることも確認しておく。
flashの表示
flashをレイアウトに追加して表示できるようにする。
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <% flash.each do |message_type, message| %>
        <div class="alert alert-<%= message_type %>"><%= message %></div>
      <% end %>
      <%= yield %>
      <%= render 'layouts/footer' %>
      <%= debug(params) if Rails.env.development? %>
    </div>
    .
    .
    .
  </body>