LoginSignup
20
25

More than 5 years have passed since last update.

RailsのRSpecでセッション情報を設定する方法

Posted at

コントローラでセッションの値を参照していて、RSpec でセッションの値を変更したテストを書く方法です。

まず、セッション追加メソッドを定義します。

# spec/support/spec_test_helper.rb

module SpecTestHelper
  def add_session(arg)
    arg.each { |k, v| session[k] = v }
  end
end

RSpec.configure do |config|
  config.include SpecTestHelper, type: :controller
end

この時、spec_test_helper.rb がロードされる必要があります。例えば rails_helper.rb にて次の様にします。

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

以上で準備は終了です。テストで追加メソッドを呼び出してみます。

describe ApplicationController, type: :controller do

  include SpecTestHelper

  it 'say hello elon' do
    session = {
      'user_name' => 'elon',
      'sex'       => 'male'
    }
    add_session(session)
    get :hello
  end

  it 'say hello tosca' do
    session = {
      'user_name' => 'tosca',
      'sex'       => 'female'
    }
    add_session(session)
    get :hello
  end

アクション内でセッションに設定されている事が確認できます。

class ApplicationController < ActionController::Base

  def hello
    session['user_name']
    # => 'say hello elon' では 'musk'
    # => 'say hello tosca' では 'tosca'
    session['sex']
    # => 'say hello elon' では 'male'
    # => 'say hello tosca' では 'female'

    # etc...
  end

当初、RSpec 内で ActionController::Metal を再オープンしたり、セッション追加アクションを定義して routes でテストの時のみ有効にしたりしていましたが、上記の方法がシンプルかなと思います。

参考

20
25
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
20
25