14
8

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 5 years have passed since last update.

コントローラのテストをRequest specで書く際に、session値を設定する

Last updated at Posted at 2019-06-14

はじめに

テスト対象外のロジック(sessionの取得)が原因でテストが進まなかったため、
session値を設定する必要がありました

##動作環境
RSpec 3.7

##テストの対象ソース

Orders_Controller.rb

class OrdersController < ApplicationController
  include SessionHelper
  before_action :authorized_user, only: [:index, :show, :edit, :update]

  def index
    @user = current_user
    @orders = @user.orders
  end
end
session_helper.rb

class SessionHelper
  def current_user
    token = session[:token]
    if token.present?
      @user ||= User.find_by(id:session[:user_id])
    end
  end
end

##エラーが出た書き方

orders_controller_spec.rb
require 'rails_helper'

RSpec.describe OrdersController, type: :request do

  describe "GET #index" do

    let(:user)  { create(:user) }
    let(:order) { create(:order, user_id, user.id) }

    it 'リクエストは200 OKとなること' do
      get orders_url , params: { session: { token: user.token, user_id: user.id } }
      expect(response.status).to eq 200
    end
  end
end

##エラー内容

コンソール
  1) OrdersController GET #index リクエストは200 OKとなること
     Failure/Error: @orders = @user.orders
     NoMethodError:
       undefined method `orders' for nil:NilClass

##サクセスした書き方

orders_controller_spec.rb
require 'rails_helper'

RSpec.describe OrdersController, type: :request do

  describe "GET #index" do

    let(:user)  { create(:user) }
    let(:order) { create(:order, user_id, user.id) }

    before do
      allow_any_instance_of(ActionDispatch::Request).to receive(:session).and_return({ remember_token: user.remember_token, remember_user_id: user.id })
    end

    it 'リクエストは200 OKとなること' do
      get orders_url
      expect(response.status).to eq 200
    end
  end
end

このようにスタブ化することで、sessionを設定できました

こちらの記事を参考にさせていただきました

14
8
1

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
14
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?