【rails】system spec(profile・trait)

※本サイトで紹介している商品・サービス等の外部リンクには、アフィリエイト広告が含まれる場合があります。

プロフィールのテストをする

ログインしているとき、プロフィールを確認できるかテストする

プロフィールを作る際、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


profileの内容を作成する

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歳で誕生日を適当に作成

今まで最初にusercreateしていた

usercreateしたときにprofileもあわせて作成されるようにしたい


trait 関連したデータを一緒に作れるようにする

userを作ったとき、profileも一緒に作る

spec/system/profile_spec.rbを開く

usercreateするとき、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

userbuildされたら(after)、profilebuildされる

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も保存される

userprofileがセットで同時に出来上がった

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