
devise を導入③
devise を導入② の続き。
ログインの挙動を確認するため以下のコードを追加する。application_controller.rb に追加。
before_action :authenticate_user!
以下のコマンドを実行してコントローラを追加する。helperは今回使用しないのでオプションを追加する。
rails g controller users index --no-helper
ログインできるか、テストを追加して確認する。
以下のコードを spec/rails_helper.rb に追加する。
config.include Devise::Test::IntegrationHelpers, type: :request
config/application.rb に以下を追加する。すでに追加されていれば問題ない。
config.hosts << '.example.com'
spec/requests/users_spec.rb に以下を追加する。ログインが成功すれば、/users/sign_in あるいは /users/sign_up 以外のページにアクセスできることを確認する目的。
以下のコードはFactoryBotが導入されている前提のコードとなっている。まだ導入されていない場合は、FactoryBot を導入 を参考に入れてみる。
let(:user) { create(:user) }
describe 'GET /users' do
before do
sign_in user
end
it 'returns http success' do
get '/users'
expect(response).to have_http_status(:success)
end
end
以下のコマンドを実行する。
rspec spec/requests/users_spec.rb
グリーンになったら成功。
.
Finished in 0.52221 seconds (files took 4.64 seconds to load)
1 example, 0 failures
次に、ログインしていない場合は /users にアクセスできないことを確認するテストを追加する。以下のように修正する。
context 'ログインしている場合' do
before do
sign_in user
end
it 'returns http success' do
get '/users'
expect(response).to have_http_status(:success)
end
end
context 'ログインしていない場合' do
it 'returns http found' do
get '/users'
expect(response).to have_http_status(:found)
end
end
以下のコマンドを実行する。
rspec spec/requests/users_spec.rb
グリーンになったら成功。
..
Finished in 0.51844 seconds (files took 4 seconds to load)
2 examples, 0 failures
テストを行なっているためブラウザで動作を確認せずともログインできることは担保されているが、一応ブラウザでの挙動確認を行う。登録済みのメールアドレスとパスワードを入力し、Log in ボタンを押す。

任意のページにリダイレクトされたら成功。
次に続く。