LoginSignup
19

More than 3 years have passed since last update.

FactoryBot で汎用的な skip Validation, save(validate: false)

Last updated at Posted at 2019-01-26

パッと見どこにも書いてなかったので覚書

FactoryBotを使ってModelを作成するとき、Validationスキップする方法としてよくある書き方

spec/factories/users.rb
FactoryGirl.define do
  factory :user do
    name 'HAZI'
    age 31

    to_create { |instance| instance.save(validate: false) }
  end
end

この方法だと、該当のモデル(この場合User)を作成するとき、全てにおいてValidationがスキップされるのでよろしくない。

なので、下記のように trait を使って create(:user, :skip_validate) と指定した時のみValidationを無効にする。

spec/factories/users.rb
FactoryGirl.define do
  factory :user do
    name 'HAZI'
    age 31

    trait :skip_validate do
      to_create { |instance| instance.save(validate: false) }
    end
  end
end

が、そもそも traitfactory メソッドの外( FactoryBot.define ブロック直下)で定義すると全てのFactoryで有効なtraitとして定義できる。

なので、 spec/factories/traits.rb などの名前でファイルを新規に作成し、そこで trait を定義をするようにすると、全てのモデルで create(:XXX, :skip_validate) が有効になる。

spec/factories/traits.rb
FactoryBot.define do
  trait :skip_validate do
    to_create { |instance| instance.save(validate: false) }
  end
end

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
19