LoginSignup
2
1

More than 5 years have passed since last update.

【RSpec】で書く「Rails Tutorial 9章(前半:〜9.19まで)」のテスト

Posted at



またまた前回に引き続き↓
【RSpec】で書く「Rails Tutorial 8章(後半:8.3)」のテスト

Rails Tutorialを進めました。

今回はその9章の途中までになります。


Rails Tutorialですること

  • Remember機能の実装
    • ユーザーが明示的にログアウトを実行しない限り、ログイン状態を維持することができる
  • Remember機能を実装するに際してバグが2つ発生
    • 1.ユーザーが1つのタブでログアウトし、もう1つのタブで再度ログアウトしようとするとエラーになる
    • 2.ユーザーが複数のブラウザ (FirefoxやChromeなど) でログインしていたときに発生。 (例えば、Firefoxでログアウトし、Chromeではログアウトせずにブラウザを終了させ、再度Chromeで同じページを開くと、この問題が発生)

今回使用するファイル

  • Spec(Request)
  • Spec(Models)
  • Controller(Session)
  • Model(User)

▼Rails TutorialのMinitest

スクリーンショット 2018-10-30 0.09.07.png

Controller(Session)

app/controllers/sessions_controller.rb
class SessionsController < ApplicationController


  def destroy
    log_out  if logged_in?
    redirect_to root_url
  end
end

Spec(Request)

spec/requests/users_login_api_spec.rb
  #9.14
  #ユーザーログアウトのテスト
  describe "<sessions#destroy>" do
    context "" do
      before do
        @user = FactoryBot.build(:user)
      end
      it "" do
        get login_path
        post login_path, params: { session: { email: @user.email, password: "password" } }

        expect(response).to have_http_status(200)
        redirect_to(@user)
        #expect(response).to redirect_to("users/show")
        expect(response).to have_http_status(200)

        delete logout_path
        expect(response).to redirect_to(root_path)

        # 2番目のウィンドウでログアウトをクリックするユーザーをシミュレートする
        delete logout_path
        follow_redirect!

        expect(response).to have_http_status(200)
      end
    end
  end

▼Rails TutorialのMinitest

スクリーンショット 2018-10-30 0.14.15.png

Model(User)

app/models/user.rb
  #渡されたトークンがダイジェストと一致したらtrueを返す
  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

Spec(Models)

spec/models/user_spec.rb
  #9.17
  it "authenticated? should return false for a user with nil digest" do
    user = User.new(name: "Example User", email: "user@example.com",password: "foobar", password_confirmation: "foobar")
    user.authenticated?("")
    expect(user).to be_truthy
  end

まとめ&反省点

Request Specのテストに関しては正直まだまだ不安が残っています。
果たしてMinitestのインテグレーションテストをRequestSpecに書いていいのかすごく悩みました。
ただ、自分の知識ではFeatureでの記述が分かりませんでした。

こちらに関してはFeatureに書くべきかRequestに書くべきか意見いただけると幸いです。

少しずつ進めていますが、RailsTutorialの難易度も上がり、
何をテストするのかが見極められなくなってきました。

少しでもおかしな部分があれば
ご指摘&アドバイスお願いします。

2
1
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
2
1