ユーザー登録時のpostリクエストのテストをrspecにてテストを行いたい。
テストコードについては、下記のとおりです。
RSpec
1require 'rails_helper' 2 3RSpec.describe 'UsersRequests', type: :request do 4 before do 5 get signup_path 6 end 7 8 describe 'users#<create>' do 9 it 'postデータの受け取りができること' do 10 user = create(:user) 11 post users_path, params: { user: user.id } 12 expect(response).to have_http_status(302) 13 end 14 end 15end
RSpec
1 2FactoryBot.define do 3 factory :user do 4 name { Faker::Name.name } 5 sequence(:email) { |n| "example#{n}@example.com" } 6 image { 'MyString' } 7 comment { 'MyText' } 8 sex { 'men' } 9 password { 'foobar' } 10 password_confirmation { 'foobar' } 11 admin { false } 12 end 13end
実際にテストを走らせると
console
1UsersRequests 2 users#<create> 3 postデータの受け取りができること (FAILED - 1) 4 5Failures: 6 7 1) UsersRequests users#<create> postデータの受け取りができること 8 Failure/Error: expect(response).to have_http_status(302) 9 expected the response to have status code 302 but it was 422 10 # ./spec/requests/users_requests_390spec.rb:14:in `block (3 levels) in <top (required)>' 11 12Finished in 0.89641 seconds (files took 1.54 seconds to load) 131 example, 1 failure 14 15Failed examples: 16 17rspec ./spec/requests/users_requests_spec.rb:11 # UsersRequests users#<create> postデータの受け取りができること
期待しているステータスコードは302 に対して結果は 422 が返っている
とのこと
ステータスコード422について調べた結果、validation errorである可能性がある。
usermodel
1class User < ApplicationRecord 2 before_save { self.email = email.downcase } 3 validates :name, presence: true, length: { maximum: 50 } 4 VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+.[a-z]+\z/i.freeze 5 validates :email, presence: true, length: { maximum: 255 }, 6 format: { with: VALID_EMAIL_REGEX }, 7 uniqueness: { case_sensitive: false } 8 validates :password, presence: true, length: { minimum: 6 } 9 has_secure_password 10 mount_uploader :image, ImageUploader 11end
ブラウザ上では、正常に動作しているようには感じます。
postリクエストのテストの仕方やステータスコード422のデバッグ方法を教えてください。
上記の他に必要なデータがございましたら、ご連絡ください。
以上、よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。