FactoryBot
FactoryBotはRailsでテストサンプルデータを簡単に扱えるように考えられたgem。
rspecと組み合わせて使われる例をよく見ます。
使い方
初期設定
spec/rails_helper.rb
config.include FactoryBot:Syntax::Methods # Rspec.configureの中に記述
Factoryの定義
spec/factories/ex.rb
FactoryBot.define do
factory :ex_user do
name {"user1"}
password {"password"}
end
end
上記の例ではfactoryの名前がex_userでその中に名前とパスワードが格納されています。
Specへ記述
specテスト内
example "xxxのテスト"
m = build(:ex_user)
end
ex_userをspec内でbuildすることで、テスト内で使用可能になる。
小技
specテスト内
example "xxxのテスト"
m = build(:ex_user, password:"hogehoge")
end
build時にobject内の値を変更することもできる。
上記はパスワードをhogehogeに変更してbuildしている。
まとめ
FactoryBotは使い勝手が良く、奥が深い。