LoginSignup
8
6

More than 3 years have passed since last update.

【RSpec】FactoryBotのモデル作成でバリデーションをスキップする方法

Posted at

テストコード用のインスタンスを作成する際、モデルにバリデーションが設定されているとバリデーションエラーによりインスタンスが作成できないときがあります。

バリデーションのチェックはスキップしていいので、とりあえずテスト用のデータを作りたいという場合は以下のようにFactoryBotでバリデーションをスキップするtraitを定義してあげるとうまくいきます。

spec/factories/users.rb
FactoryBot.define do
  factory :user do
    email 'xxx'
    ...
    ...

+   trait :skip_validate do
+     to_create {|instance| instance.save(validate: false)}
+   end
  end
end
spec/models/user_spec.rb
require 'spec_helper'

describe User do
-  let(:user) { create(:user) }
+  let(:user) { create(:user, :skip_validate) }
   ...
   ...
end
8
6
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
8
6