※本サイトで紹介している商品・サービス等の外部リンクには、アフィリエイト広告が含まれる場合があります。
プロフィールのテストをする
ログインしているとき、プロフィールを確認できるかテストする
プロフィールを作る際、factory_botに便利なメソッドがある
まず、spec/system/profile_spec.rbのファイルを作成する
require 'rails_helper'
RSpec.describe 'Profile', type: :system do
end
まずサインインしたいので、system specでもDeviceが使えるようにする
spec/rails_helperを開いて、request specと同じように書き加える
config.include FactoryBot::Syntax::Methods
config.include Devise::Test::IntegrationHelpers, type: :request
config.include Devise::Test::IntegrationHelpers, type: :system
spec/factories/profiles.rbのファイルを作成する
プロフィールの内容について、以下のように書き出す
FactoryBot.define do
factory :profile do
nickname { Faker::Name.name }
introduction { Faker::Lorem.characters(number: 100) }
gender { Profile.genders.keys.sample }
birthday { Faker::Date.birthday(min_age: 18, max_age: 65) }
end
end
- nickname 適当に作成
- introduction 100文字で作成
- gender profile.genderの中からランダム(sample)に選ぶ
- birthday 18〜65歳で誕生日を適当に作成
今まで最初にuser
をcreate
していた
user
をcreate
したときにprofile
もあわせて作成されるようにしたい
userを作ったとき、profileも一緒に作る
spec/system/profile_spec.rbを開く
「user
をcreate
するとき、profile
もあわせて作る(with_profile
)」と指定する
require 'rails_helper'
RSpec.describe 'Profile', type: :system do
let!(:user) { create(:user, :with_profile) }
end
spec/factories/users.rbを開く
trait :with_profile
が実行され、factroryが作られる
FactoryBot.define do
factory :user do
email { Faker::Internet.email }
password { 'password' }
trait :with_profile do
#ここが実行される
end
end
end
user
がbuild
されたら(after
)、profile
もbuild
される
FactoryBot.define do
factory :user do
email { Faker::Internet.email }
password { 'password' }
trait :with_profile do
after :build do |user|
build(:profile, user: user)
end
end
end
end
build
されるとsave
もされる
→ user
も保存されるし、関連しているprofile
も保存される
user
とprofile
がセットで同時に出来上がった
trait
で、関連するデータが一気に出来上がる
spec/system/profile_spec.rbを開く
これまでのことを踏まえ、以下のように書いていく
require 'rails_helper'
RSpec.describe 'Profile', type: :system do
let!(:user) { create(:user, :with_profile) }
context 'ログインしている場合' do
before do
sign_in user
end
it '自分のプロフィールを確認できる' do
visit profile_path
expect(page).to have_css('.profilePage_user_displayName', text: user.profile.nickname)
end
end
end
bundle exec rspec spec/system/profile_spec.rb
テスト成功!

#DAY15