LoginSignup
1
1

More than 3 years have passed since last update.

factory_botでモデルのenum別のtraitをまとめて書く

Posted at

はじめに

enumのtraitをひとつずつ書いていたところ、factory_botでモデルのenum別のtraitを一発で書く小ネタを見つけました。

今回、この記事とは異なる書き方でtraitを書く方法が分かったので、まとめていきます。

コード

モデル

例えば、UserがSpotifyのプランごとのステータスを持っていたとします。

app/models/user.rb
class User < ApplicationRecord
  validates :name, presence: true
  enum :plan { free: 0, individual: 1, family: 2, student: 3 }
end

このplanそれぞれにtraitを作ってもいいのですが、enumの数に比例して行数が増えます。
さらに、Spotifyにプランが追加されたときに、設定を忘れる恐れがあります。

ファクトリ

上記のモデルのtraitの行数を減らすために、このように書くことができます。

spec/factories/user.rb
FactoryBot.define do
  factory :user do
    name { "hoge" }

    User.plans.keys.each do |plan|
      trait :"#{plan}" do
        status { plan }
      end
    end

  end
end
【ポイント】
  1. enumにつけた名前を複数形にする
    この例では、plansと複数形に直しています

  2. enumの名前(複数形)のkeyを取り出す
    コンソールで表示すると以下のとおりになります。

keysで取り出すと、enumのkeyとしての名前でtraitを作ることができます!

[1] pry(main)> Tag.statuses
=> {"free"=>0, "individual"=>1, "family"=>2, "student"=>3}
[2] pry(main)> Tag.statuses.keys
=> ["free", "individual", "family", "student"]
[3] pry(main)> Tag.statuses.values
=> [0, 1, 2, 3]
1
1
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
1
1