0
0

More than 1 year has passed since last update.

[Rails] FactoryBotの実装

Posted at

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は使い勝手が良く、奥が深い。

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