kikeda1104's blog

備忘録・技術に関することを書いています。(webエンジニア)

Rspec callbackのテスト(rails)

callback(before_actionなど)で利用するメソッドのテスト方法を書いていきます。

Controller

class DashBoardController < ApplicationController
  before_action :set_user

  def index
    # ...
  end

  private
  def set_user
    @user = User.where(id: session[:user_id])
  end
end

spec

今回は指定しませんが、infer_base_class_for_anonymous_controllers = falseにすると Anonymous(匿名)クラスのデフォルト親クラスが、ApplicationControllerになります。

rspec

DashBoardController#indexのコードを上書きして、callbackにより呼ばれるメソッドの処理のみに集中できるように変えます。

RSpec.describe DashBoardController, type: :controller do
  describe 'GET #index' do
     # ...    
  end

  describe '#set_user' do
     controller do
       def index
         render text: 'success'
       end
     end  
     
     it '@userにユーザ情報がある時' do
       get :index
       expect(assigns[:user].present?).to be_truthy
     end

     it '@userにユーザ情報がない時' do
       get :index, session: { user_id: nil }
       expect(assigns[:user].blank?).to be_truthy
     end
  end
end

anonymous controller - Controller specs - RSpec Rails - RSpec - Relish