7
11

More than 3 years have passed since last update.

Rspecと Factoryの使い方

Posted at

Rspecとは?

Rspecとは自動テストをしてくれる言語。になります。
UIテストをいちいちせずとも、
「ページの遷移」、「モデルバリデーション」、「if分の条件分岐による処理の確認」...
などなど、人間がやるには面倒なことを自動でやってくれるのがRspecになります!

準備

今回は比較的簡単な、
「コントローラーによる画面遷移確認テスト」
のコードを書いていこうと思います

また、ログイン後の処理定義をするコードを書きますが、そのログイン処理をDeviseを使ってやるものとします

導入するGemインストール

今回使うのはRspecFactory_botというGemを使います
内容については後ほど解説しますので、まずはインストールしましょう!!

Gemfile
group :development, :test do
  gem "rspec-rails"
  gem "factory_bot_rails"
end

rspecを設定・書くためのファイルを作成

$ bundle exec rails generate rspec:install

deviceログインの簡略化

controller_macros

spec/support/controller_macros.rbににログイン処理を簡略化させるためのコードを記載します
ファイルがない場合のファイルを作成してください

spec/support/controller_macros.rb
module ControllerMacros
  def login_admin(admin)
    @request.env["devise.mapping"] = Devise.mappings[:admin]
    sign_in admin
  end

  def login_user(user)
    controller.stub(:authenticate_user!).and_return true
    @request.env["devise.mapping"] = Devise.mappings[:user]
    sign_in user
  end
end

rails_helperで読み込み設定

先ほどのコードを読み込ませるために、spec/rails_helper.rbに以下文を追記します

spec/rails_helper.rb
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

実装

ここからファイルに必要なコード書いていきます

テストするためのモデルを作成

spec/fatoriesこのディレクトリに作成していモデルデータを記載していきます。
今回はユーザによる画面遷移テストを作りたいので、まずユーザーファイルを作成。

spec/fatories/users.rb

その後中身を書いていきます

**spec/fatories/users.rb**
FactoryBot.define do
  factory :user do
    name { "test" }
    email { "user@email.com" }
    password { "password" }
    password_confirmation { "password" }
  end
end

今回はユーザー必要最低限な情報だけにしておきます
ここはかくじ必要なカラム等追加していただければと思います!

テストコードの記載

ここから肝心なテスト内容を記載するところです

テストコードを書く場所は
spec/controllers/users_controller_spec.rb
ここになります!
コントローラー内での画面遷移テストしかできないので、他のモデルが絡むときは
随時それ対応するコントローラーでかきましょう!

spec/cotrollers/users_controller_spec.rb
require 'rails_helper'

describe UsersController, type: :controller do
  before do
    @user = FactoryBot.create(:user)
  end
  context 'ログイン後' do
    before do 
      login(@user)
    end

    it 'トップ画面にいく' do 
      get :index
      expect(response).to have_http_status "200"
    end
  end

  context '未ログインの場合' do
    it 'トップに行くと302(エラー)が返される' do 
      get :index
      expect(response).to have_http_status "302"
    end
    it 'トップに行くとuserログインページにリダイレクトされる' do 
      get :index
      expect(response).to redirect_to new_user_session_path
    end
  end
end

・describe
 →コントローラーしていし、typeでもコントローラーと指定する
 →モデルの場合typeはmodelになる

・before do
 →テスト実行前の準備する場所
 →今回で言うとここでユーザーの情報を作成して、@userに代入してuserのデータを扱えるようにしている

・contxt
 →実行する前提条件の定義を日本語わかりやすく、みやすくする
 →実行範囲内を定義する意味もある

・it
 →実際にテストする内容

・get: :index
 →ルーティングで定義てしてるgetメソッドindexアクションに遷移すると定義

・expect(response).to have_http_status "200"
 →要するに成功したら200って返ってくきてるよね??という確認
 →ここがtrueかfalseかでテスト結果を判定している

実行


$ rspec

以上で実行完了

まとめ

以上でコントローラーテストの簡易的な説明になります
まずは簡単なところからはじめて徐々にできる範囲を伸ばしていきましょう!!

7
11
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
7
11