Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryGirlでユニーク制約のあるデータを扱う

Last updated at Posted at 2012-10-07

FactoryGirlでユニーク制約のあるデータを扱った場合、データのクリアなどの挙動の変化によりテストが成功したり失敗したりすることがある。

Userモデルが validate_uniqueness_of :email だったり
データベースにemailのunique制約がある時など

initialize_withを使う

spec/factories/user.rb
FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "person#{n}@example.com" }

    initialize_with { User.find_or_create_by_email(email)}
  end
end

参考:Stackoverflow(Using factory_girl in Rails with associations that have unique constraints)

14
13
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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?