5
0

More than 1 year has passed since last update.

【Rspec】turbo_streamを使っているときのrequest specの書き方

Last updated at Posted at 2022-03-14

はじめに

Rails7 からはバリデーションの失敗時は status: :unprocessable_entity をつける必要があります。
しかし request spec で書いている時、バリデーション失敗時でにリクエストのステータスが 200 で帰ってきてしまう

やりたい事

バリデーション失敗時のレスポンスのステータスが 422にする

環境

  • Rails 7.0.22
  • Ruby 3.1.1
  • rspec-rails 5.1.0

request spec

Rails7 から form の送信はデフォルトで Turbo_stream を利用するようになりました。
turbo_stream 利用時はレスポンスのヘッダーに Accept: 'text/vnd.turbo-stream.html' が追加されるので、spec の送信時にもヘッダーを追加する必要があります。

rails/spec/request/user.rb
require 'rails_helper'

RSpec.describe 'Registrations', type: :request do
  let(:user) { create(:user) }

  describe 'POST /users' do

    # 省略

    context 'failure' do
      it 'リクエストが失敗(nameが空)' do
        post user_registration_path, params:
        { user: {
          name: '',
          email: 'test@example.com',
          password: 'password',
          password_confirmation: 'password' } },
        xhr: true, headers: { Accept: 'text/vnd.turbo-stream.html' } #この行を追加する
      end
    end
  end
end

参考

参考をなった記事たち

Rails 7.0 + Ruby 3.1 でゼロからアプリを作ってみたときにハマったところあれこれ

Rails7 で Devise を利用する方法

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