LoginSignup
0
0

More than 1 year has passed since last update.

railsチュートリアル第八章 ユーザー登録時のログイン

Posted at

ユーザー登録時のログイン

ユーザー登録中にログインを済ませておくことにします。

ユーザー登録中にログインする

app/controllers/users_controller.rb

class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
    # データベースからユーザー情報を取り出す
  end

  def new
    @user = User.new
    #新しくユーザーオプジェクトを作成する
    # オブジェクトの属性をつける
  end

  def create
    @user = User.new(user_params)
    # 外部メソッドを使う
    if @user.save
      # 保存の成功をここで扱う。
      log_in @user
      # 登録後に自動ログインするため
      flash[:success] = "Welcome to the Sample App!"
      # 成功時一度だけ表示されるメッセージ
      redirect_to @user
      # urlを指定して表示する
      # 保存成功したらurlを表示する
    else
      render 'new'
      # 保存に成功しなければnewアクションに移動する
      # 失敗したらまた戻る
    end
  end

  private
  #外部から使えないようにする

    def user_params
    # Usersコントローラの内部でのみ実行される
    # Web経由で外部ユーザーにさらされない
       params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end
end

テスト中のログインステータスを論理値で返すメソッド

test/test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!

class ActiveSupport::TestCase
  # Run tests in parallel with specified workers
  parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all
  include ApplicationHelper

  # Add more helper methods to be used by all tests here...

  def is_logged_in?
    !session[:user_id].nil?
    # ログイン中であるかを確認
    # trueを返す
  end
end

ユーザー登録後のログインのテスト

test/integration/users_signup_test.rb

require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest
  test "invalid signup information" do
    get signup_path
    # signupのページにアクセス
    assert_no_difference 'User.count' do
    # ユーザー数が変わらないかをテストする
      post users_path, params: { user: { name:  "",
                                 # ハッシュのハッシュのようになっているように見える
                                         email: "user@invalid",
                                         password:              "foo",
                                         password_confirmation: "bar" } }
      # postリクエストを送信 フォーム送信をテストする
      # データの投稿した後 assert_no_difference で違いを比べるらしい。
    end
    assert_template 'users/new'
  end

  test "valid signup information" do
    get signup_path
    assert_difference 'User.count', 1 do
    # 
    # 第二引数でデータベースとの差異は1である。
      post users_path, params: { user: { name:  "Example User",
                                         email: "user@example.com",
                                         password:              "password",
                                         password_confirmation: "password" } }
    end
    follow_redirect!
    # POSTリクエストを送信した結果を見て、指定されたリダイレクト先に移動するメソッド
    assert_template 'users/show'
    # showアクションのビューを表示させる。
    assert is_logged_in?
    # ログイン中であるかを確認

  end
end
ubuntu:~/environment/sample_app (basic-login) $ rails t
Running via Spring preloader in process 6231
Started with run options --seed 6084

  24/24: [============================] 100% Time: 00:00:02, Time: 00:00:02

Finished in 2.63192s
24 tests, 54 assertions, 0 failures, 0 errors, 0 skips

演習

1.
リスト 8.29のlog_inの行をコメントアウトすると、テストスイートは red になるでしょうか? それとも green になるでしょうか? 確認してみましょう。

ubuntu:~/environment/sample_app (basic-login) $ rails t
Running via Spring preloader in process 6664
Started with run options --seed 61607

 FAIL["test_valid_signup_information", #<Minitest::Reporters::Suite:0x00007fa7153721e8 @name="UsersSignupTest">, 2.3977448109999386]
 test_valid_signup_information#UsersSignupTest (2.40s)
        Expected false to be truthy.
        test/integration/users_signup_test.rb:34:in `block in <class:UsersSignupTest>'

  24/24: [============================] 100% Time: 00:00:02, Time: 00:00:02

Finished in 2.83391s
24 tests, 54 assertions, 1 failures, 0 errors, 0 skips

ログインされていないからエラーになったらしい。

2.
現在使っているテキストエディタの機能を使って、リスト 8.29をまとめてコメントアウトできないか調べてみましょう。また、コメントアウトの前後でテストスイートを実行し、コメントアウトすると red に、コメントアウトを元に戻すと green になることを確認してみましょう。ヒント: コメントアウト後にファイルを保存することを忘れないようにしましょう。また、テキストエディタのコメントアウト機能については『テキストエディタ編』の 「コメントアウト機能」などを参照してみてください。

ファイルの全部をコメントアウトして確認。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0