1
0

More than 3 years have passed since last update.

[Rails]Rspecでログインユーザーを作成する方法

Last updated at Posted at 2021-03-08

はじめに

  • 自分が初めてRspec(リクエストスペック)を実装した時につまづいた。同じ人のために、記事録として作成しています。

課題

  • 200を期待しているが、302が返る
it "リクエストが成功する" do
  subject
  expect(response).to have_http_status(:ok) #=> found(302)
  #=>ok(200)を期待しているが、 found(302)が返る
end

原因

  • ログインユーザーではない場合、リダイレクトするbefore_actionを設定している

解決策

  • ユーザーをログインさせる

実装

①設定
以下のファイルにコードを追加する

rails_helper.rb
RSpec.configure do |config|  
  #以下を追加
  # リクエストスペックで Devise のテストヘルパーを使用できるようにする
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.include Devise::Test::IntegrationHelpers, type: :request
  # 以上を追加
end

②ユーザーをログインさせる
1.before do ~ endでログインユーザーを作成(テストデータはusers.rbで作成)
2.sign_in @userでユーザーをログインさせる

xxx_request_spec.rb
RSpec.describe "xxx", type: :request do
  # ログインさせるユーザーを作成
 + before do
 +   @user = create(:user)
 + end

  # 略

  it "リクエストが成功する" do
    # 先ほど作成したユーザーをログインさせる
  + sign_in @user
    subject
    expect(response).to have_http_status(:ok)
  end
end

before

it "リクエストが成功する" do
  subject
  expect(response).to have_http_status(:ok) #=> 302
  #=>ok(200)を期待しているが、 found(302)が返る
end

after

it "リクエストが成功する" do
+ sign_in @user
  subject
  expect(response).to have_http_status(:ok) #=> 200
  #=>ログインしている為、before_actionにかからなくなり、ok(200)が返る
end

今回のまとめ

  • テストを実行するとリダイレクトされてしまう(200 => 302)
  • 原因はbefore_actionで未ログインユーザーはリダイレクトするようになっている為。 →ユーザーをログインさせる必要がある
  • ユーザーをログインさせるには、sign_inを使用できるようにする必要がある
  • sign_inを使用するには、rails_helper.rbに設定を記述する必要がある
1
0
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
1
0