letを使った遅延処理
spec/system/tasks_spec.rb
require 'rails helper'
describe 'タスク管理機能', type: :system do
describe '一覧表示機能' do
let(:user_a) {FactoryBot.create(:user, name: 'ユーザーA', email: 'a@example.com')}
let(:user_b) {FactoryBot.create(:user, name: 'ユーザーB', email: 'b@example.com')}
before do
FactoryBot.create(:task, name: '最初のタスク', user: user_a)
visit login_path
fill_in 'メールアドレス', with: login_user.email
fill_in 'パスワード', with: login_user.password
click_button 'ログインする'
end
context 'ユーザーAがログインしてる時' do
let(:login_user) { user_a }
it ~~~~ do
end
end
context 'ユーザーBがログインしている時' do
let(:login_user) { user_b }
it ~~~~ do
end
end
end
end
このように先にログイン処理の大枠を書いておいて、contextごとにletで具体的なlogin_userの値を指定してる。
また、user_a,user_bの作成はbefore do end の外側で行ってる。
また、ログイン処理の大枠も、moduleに定義して他のファイルでも使い回せるようにした方がいいかも。
shared_examples
文字通り、exampleを定義して他でも簡単に使い回せるようにしよーってこと。
shared_contextのexample版
spec/system/tasks_spec.rb
require 'rails helper'
before do
FactoryBot.create(:task, name: '最初のタスク', user: user_a)
visit login_path
fill_in 'メールアドレス', with: login_user.email
fill_in 'パスワード', with: login_user.password
click_button 'ログインする'
end
shared_examples_for 'ユーザーAが作成したタスクが表示される' do
it { expect(page).to have_content '最初のタスク' }
end
describe '一覧表示機能' do
context 'ユーザーAがログインしてる時' do
let(:login_userA) { user_a }
it_behaves_like 'ユーザーAが作成したタスクが表示される'
end
end
このようにdescribeよりも前にexampleを定義して使い回す。
これもmoduleのファイルを作ってそこに定義した方が良さそう。