1
0

More than 1 year has passed since last update.

RSpecの準備、及びFactoryBot、Fakerを用いたモデルデータの設定方法について

Posted at

目的

RSpecを用いたテストの実装

前提条件

  • Ruby 3.1.2
  • Rails 6.1.7.2

RSpecの準備

Gemfile
group :test do
  gem 'capybara', '>= 3.26'
  gem 'selenium-webdriver', '>= 4.0.0.rc1'
  gem 'webdrivers'
  # RSpecテスト用
  gem 'rspec-rails'
  gem "factory_bot_rails"
  gem 'faker'
  gem 'rails-controller-testing'
end
  • rspec-rails
    RailsにてRSpecを使ってテストするのに必要
  • factory_bot_rails
    テスト用にダミーのインスタンスを作成
  • rails-controller-testing
    Railsのコントローラーをテストするのに必要
  • faker
    インスタンス作成の際、多様なダミーデータを投入できるようになる
ターミナル
$ bundle install

RSpecのファイルの作成

ターミナル
$ rails g rspec:install
.rspec
--require spec_helper
#以下追加
--format documentation

この記述で表示を以下のように変更
テスト項目が見やすくなる

ターミナル
Message
  create
    can save
      is valid with a message
      is valid with an image
      is valid with a message and an image
    can not save
      is invalid without a message and an image
      is invalid without a group
      is invalid without an user

Finished in 3.51 seconds (files took 4.50 seconds to load)
6 examples, 0 failures

factory_botの書き方を省略

spec/rails_helper.rb
RSpec.configure do |config|
  #以下を追加
  config.include FactoryBot::Syntax::Methods
end

FactoryBot、Fakerを用いたモデルデータの作成

factory_botの作成

specフォルダ配下にfactoriesフォルダを作成

ターミナル
mkdir spec/factories

さらに、作成したいファイルのモデルの作成
spec/factories/作成したいモデル名.rb
以下はuserモデルでの例

spec/factories/user.rb
FactoryBot.define do
  # パスワードの設定
  #パスワードのように同じ記述を複数回使用したい場合は以下のような変数に指定して代入することが出来る
  password = Faker::Internet.password(min_length: 6, max_length: 8)
  
  # ユーザーモデルのダミーデータ
  factory :user do
    #カラム名 { 作成したい内容を記述 }
    #Faker〜の記述はgem 'faker'を用いたダミーデータの作成を指している
    name { Faker::Internet.username(specifier: 5..8) }
    nickname { Faker::Internet.username(specifier: 5..8) }
    email { Faker::Internet.email(domain: 'example') }
    phone_number { Faker::Number.leading_zero_number(digits: 11) }
    password { password }
    password_confirmation { password }
    is_deleted { "false" }
  end
end

Fakerの使い方、書き方一覧は下記公式のREADME.mdから調べるとわかりやすい
Faker::Internetの場合、Generators項目の、Default内にある、Faker::Internetのリンクをクリックすることで確認できる

次回以降について

次回はモデルにおけるテストの作成について掲載予定です

1
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
1
0