0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FactoryBot・Fakerの導入

Posted at

目的

Railsで作成したアプリにFactoryBotFakerを導入する。

開発環境

macOS: Big Sur
Rubyバージョン: 2.6.5
Railsバージョン: 6.0.0

前提

手順

FactoryBotとは

インスタンスをまとめることができるGemです。
あらかじめ各クラスのインスタンスに定める値を設定しておき、テストコードで使用します。

Fakerとは

ランダムな値を生成してくれるGemです。
FakerのGitHub
こちらの公式GitHubにもあるように、様々な値が生成可能です。

Gemのインストール

Gemfileを以下のように編集します。
この時、group :development, :test doの中に記述するように注意してください。

Gemfile
group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails', '~> 4.0.0'
  gem 'factory_bot_rails'
  gem 'faker'
end
ターミナル
% bundle install

これでインストールできました!

記述法

以下のように記述することができます!

spec/factories/users.rb
FactoryBot.define do
  factory :user do
    nickname              {Faker::Name.initials(number: 2)}
    email                 {Faker::Internet.free_email}
    password              {Faker::Internet.password(min_length: 6)}
    password_confirmation {password}
  end
end

最後に

以上で導入は完了です。
Gemでインストールするのみなので非常に簡単に実装できます。
では。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?