0
0

More than 1 year has passed since last update.

重複のバリデーションエラーを回避するFactoryBotの書き方

Posted at

目的

Userモデルにてemailの一意性をバリデーションとして設定している場合、下記のテストコードではエラーが発生する。

FactoryBot.define do
  factory :user do
    user_name { "tester" }
    email { "tester@example.com" }
    password { "password" }
  end
end
it "複数のユーザー登録" do
    user1 = FactoryBot.create(:user)
    user2 = FactoryBot.create(:user)
  end

エラーが発生しないように複数のテストユーザーを作成する。

実装方法

FactoryBot.define do
  factory :user do
    user_name { "tester" }
		#シーケンスを利用する
    sequence(:email) { |n| "tester#{n}@example.com" }
    password { "password" }
  end
end

上記の記述により「tester1@example.com」「tester2@example.com」のようにユニークなemailが出力される。

注意点・メモ

Factory_Botのシーケンスにはさまざまな利用方法があるので理解しておくこと。

参考サイト・資料

Qiita:【RSpec】重複のバリデーションエラーを回避するFactoryBotの書き方

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0