前提
現在「現場で使えるRuby on rails5速習実践ガイド」という書籍を参考にしながらタスク管理アプリを作成しております。
教材を参考にコードを書き、bundle spec rspec spec/system/tasks_spec.rbを実行したところ、以下のエラーが発生しました。
発生している問題・エラーメッセージ
DEBUGGER: Attaching after process 97910 fork to child process 97932 ..F Failures: 1) タスク管理機能 詳細表示機能 ユーザーAがログインしているとき ユーザーAが作成したタスクが表示される Failure/Error: expect(page).to have_content '最初のタスク' expected to find text "最初のタスク" in "Taskleaf\nログイン\nログイン\nメールアドレス\nパスワード" [Screenshot Image]: /Users/sampleuser/taskleaf/tmp/capybara/failures_r_spec_example_groups_nested_nested_2_a_ユーザーaが作成したタスクが表示される_935.png # ./spec/system/tasks_spec.rb:42:in `block (4 levels) in <top (required)>' Finished in 9.74 seconds (files took 2.02 seconds to load) 3 examples, 1 failure Failed examples: rspec ./spec/system/tasks_spec.rb:41 # タスク管理機能 詳細表示機能 ユーザーAがログインしているとき ユーザーAが作成したタスクが表示される
spec/system/tasks_spec.rb
1require 'rails_helper' 2 3describe 'タスク管理機能', type: :system do 4 let(:user_a) { FactoryBot.create(:user, name: 'ユーザーA', email: 'a@example.com') } 5 let(:user_b) { FactoryBot.create(:user, name: 'ユーザーB', email: 'b@example.com') } 6 let!(:task_a) { FactoryBot.create(:task, name: '最初のタスク', user: user_a) } 7 8 before do 9 visit login_path 10 fill_in 'メールアドレス', with: login_user.email 11 fill_in 'パスワード', with: login_user.password 12 click_button 'ログインする' 13 end 14 15 describe '一覧表示機能' do 16 context 'ユーザーAがログインしているとき' do 17 let(:login_user) { user_a } 18 19 it 'ユーザーAが作成したタスクが表示される' do 20 expect(page).to have_content '最初のタスク' 21 end 22 end 23 24 context 'ユーザーBがログインしているとき' do 25 let(:login_user) { user_b } 26 27 it 'ユーザーAが表示したタスクが表示されない' do 28 expect(page).to have_no_content '最初のタスク' 29 end 30 end 31 end 32 33 describe '詳細表示機能' do 34 context 'ユーザーAがログインしているとき' do 35 let(:login_user) { user_a } 36 37 before do 38 visit task_path(task_a) 39 end 40 41 it 'ユーザーAが作成したタスクが表示される' do 42 expect(page).to have_content '最初のタスク' 43 end 44 end 45 end 46 47end
本来task_path(task_a)に遷移したいのですが、なぜかloginページに遷移して、テストが失敗します。
確かに、ログインしていないとloginページにリダイレクトされるようにしていますが、user_aでログインが成功しているのに何故??っていう感じです・・・。
該当のソースコード
application_controller.rb
1class ApplicationController < ActionController::Base 2 helper_method :current_user 3 before_action :login_required 4 5 private 6 7 def current_user 8 @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id] 9 end 10 11 def login_required 12 redirect_to login_url unless current_user 13 end 14end
補足情報(FW/ツールのバージョンなど)
rails 7.0.3.1
rspec 3.11
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/08/20 02:25
2022/08/20 02:39
2022/08/20 02:50
2022/08/20 05:59