🖥
RailsのFactoryBot で transient / association / before create / aftter cr
- コードはイメージである
- DSLなので?わりと上から順に評価してくれる気がする
- transient や after や before やらをさんざんとこねくり回したあげく、attributes を上から一つずつ順に書いていって、if else などで分岐させる方法が落ち着きや良さそうなことに気づいた状態
FactoryBot.define do
factory :user do
trait :student do
state { :student }
end
friend do
if state == :student
create :friend
else
nil
end
end
friend_name { friend ? friend.name : (create :friend).name }
end
end
FactoryBotというDSLはなかなか手ごわい
- 柔軟なことをしようとすると途端に行き詰まる感じがする
- ひとつが成り立つと1つが成り立たず、関連テストがばったばったと落ちたりする。
- 評価順は trait -> transient -> before -> after だろうか?そんな単純な話ではないのかもしれないし、あるのかもしれない。
- DSL なので do end の中で binding.pry しても、実行時のデバッグができるわけではない。
Original by Github issue
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2019-10-26
Discussion