記事概要
Ruby on RailsのFactoryBot(Gem)について、まとめる
前提
- Ruby on Railsでアプリケーションを作成している
FactoryBotとは
インスタンスをまとめることができるGem
他のファイルであらかじめ各クラスのインスタンスに定める値を設定しておき、各テストコードで使用する
Gemのインストール手順
Gemfileの記述
手順(設定)
- インスタンスの生成を切り出すファイルを作成する
- FactoryBot導入前に、テストコードを記述するファイルを生成
-
spec
配下に、factories
フォルダを手動作成 -
factories
フォルダに、[モデル名の複数形].rb
を手動作成
-
- FactoryBot導入後に、テストコードを記述するファイルを生成
-
spec/factories/[モデル名の複数形].rb
が自動生成される
-
- FactoryBot導入前に、テストコードを記述するファイルを生成
- 上記で作成したファイルを編集
-
Fakerを使い、ランダム値を入力
spec/factories/users.rb
FactoryBot.define do factory :user do nickname {Faker::Name.initials(number: 2)} email {Faker::Internet.email} password {Faker::Internet.password(min_length: 6)} # password_confirmationはpasswordと同じ値なので、「password」を指定 password_confirmation {password} end end
- 固定値を入力
spec/factories/users.rb
FactoryBot.define do factory :user do nickname {'test'} email {'test@example'} password {'000000'} # password_confirmationはpasswordと同じ値なので、「password」を指定 password_confirmation {password} end end
-
Fakerを使い、ランダム値を入力
まとめ
ダミーデータに画像を添付
テスト用ダミー画像public/images/test_image.png
をインスタンスに付与する
messages.rb
FactoryBot.define do
factory :message do
content {Faker::Lorem.sentence}
after(:build) do |message|
# io: File.openで設定したパスのファイル(public/images/test_image.png)を、test_image.pngというファイル名で保存
message.image.attach(io: File.open('public/images/test_image.png'), filename: 'test_image.png')
end
end
end
インスタンスに画像が添付できているかを確認する方法
- コンソールを起動する
% rails c
- 画像が保存できているか確認する
[1] pry(main)> message = FactoryBot.create(:message) #=> 省略 [2] pry(main)> message.image.attached? => true
Ruby on Railsまとめ