LoginSignup
17
13

More than 5 years have passed since last update.

request spec で session 値を設定する

Posted at

検索すると……

https://github.com/rails/rails/issues/23386#issuecomment-273602172 のような感じでリクエストするときにCookieヘッダーでセッションクッキーを送るというものが引っかかります。
なお、このコメントで示されているコードは Rails 5.2.3 / Rspec 3.8.0 ではうまく動きませんでした。
// ENV.fetch('SECRET_KEY_BASE')Rails.application.credentials.secret_key_base としたり、もろもろ変えてもだめでした。
// もっと変える必要がありそうではあるけど、私にはわからなかった。

ちなみにDHHは上記のissueのコメントで、セッションを作るURLに post なりするのがいいと述べています。

よくよく考えると…

セッションクッキーがリクエストに乗ってきて、それをどうこうする部分をテストしたいわけではないので前述の方法は不要で、セッションから取れる値をスタブできればいいのです。

コード例

describe 'セッションをスタブする', type: :request do
  context do
    let(:user) { create(:user) }
    before 'ユーザーIDをセッションから取り出せるようにする' do
      allow_any_instance_of(ActionDispatch::Request)
        .to receive(:session).and_return(user_id: user.id)
    end

    it '/hoge が成功してユーザー情報が○○する' do
      get '/hoge'

      expect(response).to be_successful
      expect(User.find user).to have_attributes(
        hoge: 'fuga'
      )
    end
  end
end

and_return に渡すHashオブジェクトを好きなものにすればOKです。

17
13
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
17
13