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?

【Rails】Faker(Gem)について

Last updated at Posted at 2025-05-06

記事概要

Ruby on RailsのFaker(Gem)について、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している

Fakerとは

ランダムな値を生成するGem

Gemのインストール手順

Gemfileの記述

手順

  1. テストファイルにコードを記述する

参考コード

ユーザー

# 「password_confirmation」の値は、「password」と同じなので、「password」を指定
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}
  end
end

記述様式

公式サイトのドキュメント参照

Faker::Name.name
#=> "Christophe Bartell"

Faker::Address.full_address
#=> "5479 William Way, East Sonnyhaven, LA 63637"

Faker::Internet.email
#=> "eliza@mann.test"

# Fakerで生成されるパスワードは、デフォルト値が8文字以上16文字以下
Faker::Internet.password
#=> "Vg5mSvY1UeRg7"

Faker::Lorem.word
#=> "repellendus"

Faker::Lorem.sentence
#=> "Quia illum libero magni."

日本語対応

  1. 設定ファイルを変更する
    config/application.rb
    class Application < Rails::Application
    	config.i18n.default_locale = :ja # 追記
    end
    
  2. 日本語で値を作成できるようになることを確認する(カナ対応はしていない)
    irb(main):001:0> Faker::Name.name
    => "野村 翼"
    irb(main):002:0> Faker::Name.first_name
    => "美桜"
    
  3. テストファイルを更新する

備考

Ruby on Railsまとめ

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?