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

RSpec sequenceについて

Last updated at Posted at 2021-10-17

RSpecとは

RailsでWebアプリを開発する時に想定通りの挙動になるかを
検証するためのテストフレームワークです。

sequenceとは

sequenceとは順序という意味の単語です。
FactoryBotを使う時にバリデーションに引っかからないように
データが重複しないことを防ぐためのものです。
FactoryBot.createやFactoryBot.buildを使い、
複数個データが作成した時にデータ番号をそれぞれ作成できます。

sequenceの使い方

sequenceの使い方を見ていきましょう。
下が構文です。

~.spec.rb
FactoryBot.define do
  factory :モデルクラス名 do
    sequence(:カラム名) { |n| "ここに#{n}連番を挿入" }
  end
end

※下の資料から引用

staffモデルとして説明します。

staffs_spec.rb

FactoryBot.define do
  factory :staff do
    name {Faker::Name.name}
    sequence(:job) {|n|  "#{n}_#{Faker::Job.field}"}
    sequence(:idnumber)  {|n| "#{n}_#{Faker::IDNumber.valid}"}
end
end

これでnを1ずつ増やして行ってもデータは重複しなくなります。
コンソールを立ち上げて見て
FactoryBot.create(:staff)かFactoryBot.build(:staff)
あたりで調べていくとidが1ずつ増えていくのがわかるかと思います。

参考資料

https://qiita.com/9-michi-9/items/fa009d725dfeba56b22a
http://www.code-magagine.com/?p=9687
https://nowdeveloping.blogspot.com/2016/10/factorygirlsequence.html

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