👌

RSpecテスト④(FactoryBot, with: user_attributes,実行コマンド)

2025/03/12に公開

そもそもFactoryBotとは?

テスト用のダミーデータを簡単に作成するためのライブラリ。
spec/factories/モデル名.rbに記入する。
(今回間違えてmodelsフォルダ内に書いてたので注意)

spec/factories/user.rb

FactoryBot.define do
  factory :user do
    name { Faker::Name.name }
    email { Faker::Internet.email }
    password { "password" }
  end
end

spec/factories/task.rb

FactoryBot.define do
  factory :task do
    title { "カリキュラムを5ページ進める" }
    keyword1 { "Ruby" }
    keyword2 { "テスト" }
    keyword3 { "エンジニア" }
    association :user # `user` を自動で作成
  end
end

FactoryBotを使用することでコードを短くできる。

FactoryBot使用前

let(:user) { FactoryBot.create(:user) }
let!(:task) { FactoryBot.create(:task, user: user, title: "カリキュラムを5ページ進める", keyword1: "Ruby", keyword2: "テスト", keyword3: "エンジニア") }

FactoryBot使用後

let!(:task) { create(:task) } # `task` を作ると、自動で `user` も作られる
let(:user) { task.user } # 明示的に `user` を取得したい場合

association :user

「association :user」は、FactoryBot の機能で、Task に関連する User を自動で作成する。

Taskモデル は belongs_to :user という関連を持っている。

class Task < ApplicationRecord
  belongs_to :user
end

そのため、Task を作成するときは 必ず user_id をセットする必要がある。
association :user を書くと、FactoryBot が User のデータを自動で作成し、user_id にセットしてくれる。

attributes_for(:user) とは?

attributes_for(:user) は FactoryBot のメソッドで、データベースに保存せずに、ユーザー情報のハッシュを作成する もの。

with: user_attributesで、ユーザーの属性(name, email, password など)を含むハッシュデータを引数として渡している。

RSpec.describe "トップページのテスト" do
    let(:user_attributes) { attributes_for(:user) }
    context "新規登録処理のテスト" do
      it "正しい情報の場合、新規登録が完了する" do
        visit new_user_registration_path
        fill_in 'user_name', with: user_attributes[:name]
        fill_in 'user_email', with: user_attributes[:email]
        fill_in 'user_password', with: user_attributes[:password]
        fill_in 'user_password_confirmation', with: user_attributes[:password]
        click_button '登録'

        expect(page).to have_content 'アカウント登録が完了しました。'
      end
    end
end

RSpecテストを実行するコマンド

1. 全てのテストを実行

bundle exec rspec

2. 特定のファイルだけ実行

bundle exec rspec spec/system/user_spec.rb

3. 特定のテストケースのみ実行

bundle exec rspec spec/system/user_spec.rb:34

4. 直前に失敗したテストだけ再実行

bundle exec rspec --only-failures

spec/rails_helper.rb または spec/spec_helper.rb に以下を追加

RSpec.configure do |config|
  config.example_status_persistence_file_path = "tmp/rspec_failures.txt"
end

5. テストの詳細ログを表示

bundle exec rspec --format documentation

6. テストの進行状況をカラフルに表示

bundle exec rspec --color --format documentation

Discussion