6
0

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 3 years have passed since last update.

Rspec、FactoryBotで使う【sequence】って何?

Last updated at Posted at 2022-01-28

sequence(シーケンス)とは

tasks.rb
FactoryBot.define do
  factory :task do
    sequence(:title, "title_1") #ここ
    content { "content" }
    status { :todo }
    deadline { 1.week.from_now }
    association :user
  end
end

:task do内の1行目にある
**sequence(:title, "title_1")**このsequenceにあたる。

コンソール.
'title_1'.next
=> "title_2"

'title_7'.next
=> "title_8"

title_1.nextをつけてコンソールで確認してみると、次の数字が含んだtitle_2となった。

sequenceの単語の意味は「順番・順序」となるので、.nextで次の数字が表示される意味となったのかも。

.nextはruby自体の機能で、末尾の数値を増やす機能がある

ただしこれを日本語でやろうとすると、

コンソール.
'タスク_1'.next
=> "タスク_2"

'タスク_9'.next
=> "タスグ_0"

9の次が0になっていたり、タスグとなっていたりして正しく表示されていない。
英字 + 記号 + 数字が発動条件のよう。

他にも

コンソール.
sequence(:reserve_on, Date.today)
# 今日、明日、明後日、という感じで順に生成される

sequence(:color, %w[red green blue].cycle)
# cycleを使うと、red green blue がこの順番で繰り返される

cycleは本番環境では上手くいかないので注意。

user.rb
sequence(:email) { |n| "user_#{n}@example.com" }

user1 = FactoryBot.create(:user)
# 結果→ example1@example.com

user2 = FactoryBot.create(:user)
# 結果→ example2@example.com

このファクトリが呼び出されるたびに、nの部分に数字が一つずつ増えて入るため、一意性が保たれる。

参考記事

FactoryBot (旧FactoryGirl) の sequence と .next

6
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
6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?