LoginSignup
7
7

More than 5 years have passed since last update.

FactoryGirlで連番使って重複しないデータの作成

Last updated at Posted at 2015-10-02

emailとかユニーク制約がついているカラムに対してFactoryGirlでは、シーケンスを利用してユニークのデータを作成することができます。

連番(Sequences)の使用例

usernameに連番を使って、ユニークしてそれをemail作成している例

FactoryGirl.define do
  factory :user do
    # test.user1, test.user2, test.user3, ... 
    sequence :username do |n|
      "test.user#{n}"
    end
    email { "#{username}@example.com" }
    password 'password'
  end
end

初期値を設定する例

FactoryGirl.define do
  factory :user do
    # test.user100, test.user101, test.user102, ... 
    sequence :username,100 do |n|
      "test.user#{n}"
    end
    email { "#{username}@example.com" }
    password 'password'
  end
end

数字以外を設定する例

FactoryGirl.define do
  factory :user do
    # test.usera, test.userb, test.userc, ... 
    sequence :username,'a' do |n|
      "test.user#{n}"
    end
    email { "#{username}@example.com" }
    password 'password'
  end
end
7
7
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
7
7