0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[RSpec] shared_contextで共通化

Posted at

はじめに

RSpecでログイン「状態」にしたいなどの共通処理を作成するための方法

APIモードでJWTでの認証方式を利用している。

以下2つが利用できるように共通化する
login_user: ユーザーのインスタンス
headers: login_userに紐づくaccess_tokenをBeare tokenに設定sheaders

必要な設定

# spec/rails_helper.rbの以下のコメントアウトを解除
ails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }

基本

# spec/support/contexts/login_setup.rb
# 処理定義
RSpec.shared_context 'login setup' do
...
end

# 使用先
include_context 'login setup'

spec/support/contexts/login_setup.rb
letを使うかbefore doブロックを使用する

RSpec.shared_context 'login setup' do
  User.destroy_all
  let(:login_user) { create(:user, password: "Password1234!") }
  let(:login_headers) do
    post "/login", params: { user: { email: login_user.email, password: "Password1234!" } }
    token = body["token"]
    { "ACCEPT" => "application/json", "Authorization" => "Bearer #{token}" }
  end
end
describe "PUT /users/'id" do
    include_context 'login setup'

    it 'ユーザーを更新できる' do
      put "/users/#{login_user.id}",
        params: { user: { email: "updated@gmail.com", password: "Password1234!" } },
        headers: login_headers # ログイン状態にする

      expect(response).to be_successful
      expect(body['email']).to eq('updated@gmail.com')
    end
  end
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?