4
0

More than 3 years have passed since last update.

【RSpec devise_token_auth 】ユーザー認証トークンを渡す方法

Posted at

はじめに

devise_token_authを使用してユーザー認証をrequest specに書く際に時間がかかったので、他に同じ様なエラーで詰まっている方のお役に立てれば幸いです。

前提

Ruby:2.6.5
Rails:6.0.3.1

テストはRSpecを使用。
ユーザー認証にdevise_auth_tokenを使用しています。

失敗するspec

shops_request_spec.rb
RSpec.describe "Api::V1::Shops", type: :request do
  describe "GET api/v1/shops" do
    let!(:shops) { create_list(:shop, 10) }
    context "認証済みのユーザーの場合" do
      it "一覧を表示できる" do
        get '/api/v1/shops'
        expect(response.status).to eq(200)
        expect(json.size).to eq(10)
      end
    end
 end

これだとユーザー認証ができずに401のエラーコードが出てテストがパスしません。

ユーザー認証トークンの渡し方

create_new_auth_tokenでトークンを作り、get '/api/v1/shops'にheadersを追加します。
※因みにトークンの認証はuid access-token clientをheadersに返してユーザー認証をしています。

shops_request_spec.rb
RSpec.describe "Api::V1::Shops", type: :request do
  describe "GET api/v1/shops" do
    let!(:shops) { create_list(:shop, 10) }
    context "認証済みのユーザーの場合" do
      let(:auth_headers) { create(:user).create_new_auth_token }
      it "一覧を表示できる" do
        get '/api/v1/shops', headers: auth_headers
        expect(response.status).to eq(200)
        expect(json.size).to eq(10)
      end
    end
 end

この様にかけば、ユーザー認証が成功します!!

参考記事

2番目の記事はやり方は違いますが、同じくdevise_auth_tokenでのユーザー認証のやり方を記載した記事なので、すごく参考になると思います!!

https://tutorialmore.com/questions-2886025.htm

https://qiita.com/mtoyopet/items/ed1bd4b9c1544d401880

おわりに

今年駆け出したばかりのエンジニアなので、何か間違っている点あればコメント等お願いします。

4
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
4
0