質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

ユニットテスト

ユニットテストは、システムのテスト手法の一つで、個々のモジュールを対象としたテストの事を指します。対象のモジュールが要求や性能を満たしているか確認する為に実行します。

Q&A

解決済

1回答

1727閲覧

rspecを用いたコントローラーのテストにおいて、DBにuser登録するテストが通らない。 新規ユーザー登録実装方法:devise/ウィザード形式

shuya-tamaru

総合スコア26

Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

ユニットテスト

ユニットテストは、システムのテスト手法の一つで、個々のモジュールを対象としたテストの事を指します。対象のモジュールが要求や性能を満たしているか確認する為に実行します。

0グッド

0クリップ

投稿2020/02/12 15:39

編集2020/02/12 15:43

Ruby on railsにてECサイトを開発中。
deviseを用いて新規ユーザー登録をウィザード形式で実装(1ページ目 ユーザー情報 → 2ページ目 携帯電話 → 3ページ目 住所 → 4ページ目 クレジッド →
登録完了!)実装は完了済み。
新規登録のcontrollerテストをrspecを用いて記述中。
4ページ目のcreate_cardメソッドにおいて、どうしてもDBにユーザーが登録されるテストが通らない。
原因はsessionがらみかなとはと思うのですが・・・ググってもなかなか解決できず、初心者で基本的なことかもしれず申し訳ありませんがご教授願います。

ERROR文

1Post #create_card 2 card is valid 3 リクエストは302 リダイレクトとなること (FAILED - 1) 4 データベースに新しいユーザーが登録されること (FAILED - 2) 5 6Failures: 7 8 1) Users::RegistrationsController Post #create_card card is valid リクエストは302 リダイレクトとなること 9 Failure/Error: expect(response.status).to eq 302 10 11 expected: 302 12 got: 200 13 14 (compared using ==) 15 # ./spec/controllers/users/registrations_controller_spec.rb:160:in `block (4 levels) in <top (required)>' 16 17 2) Users::RegistrationsController Post #create_card card is valid データベースに新しいユーザーが登録されること 18 Failure/Error: 19 expect do 20 subject 21 end.to change{User.count}.by(1) 22 23 expected `User.count` to have changed by 1, but was changed by 0 24 # ./spec/controllers/users/registrations_controller_spec.rb:169:in `block (4 levels) in <top (required)>' 25 26Finished in 0.3602 seconds (files took 1.8 seconds to load) 2717 examples, 2 failures 28 29Failed examples: 30 31rspec ./spec/controllers/users/registrations_controller_spec.rb:157 # Users::RegistrationsController Post #create_card card is valid リクエストは302 リダイレクトとなること 32rspec ./spec/controllers/users/registrations_controller_spec.rb:168 # Users::RegistrationsController Post #create_card card is valid データベースに新しいユーザーが登録されること

#registrations_controller.rb↓

ruby

1require 'rails_helper' 2 3describe Users::RegistrationsController do 4 5 describe 'Post #create_card' do 6 7#途中のテストは省略 8 9 context 'card is valid' do 10 before do 11 @request.env["devise.mapping"] = Devise.mappings[:user] 12 @user = attributes_for(:user) 13 session["devise.regist_data"] = {user: @user} 14 @cellphone = attributes_for(:cellphone) 15 @address = attributes_for(:address) 16 @card = attributes_for(:card) 17 end 18 19 subject { 20 post :create_card, params: {card: @card }, 21 session: { 22 user: @user, 23 cellphone: @cellphone, 24 address: @address 25 } 26 } 27 28 it 'リクエストは302 リダイレクトとなること' do 29 post :create_card, params: {card: @card} 30 subject 31 expect(response.status).to eq 302 32 end 33 34 it 'データベースに新しいユーザーが登録されること' do 35 expect do 36 subject 37 end.to change{User.count}.by(1) 38 end 39 end 40 end 41end 42

#registrations_controller.rb

ruby

1# frozen_string_literal: true 2 3class Users::RegistrationsController < Devise::RegistrationsController 4 before_action :configure_sign_up_params, only: [:create] 5 # before_action :configure_account_update_params, only: [:update] 6 7 # GET /resource/sign_up 8 9 def new 10 @user = User.new 11 end 12 13 # POST /resource 14 def create 15 @user = User.new(sign_up_params) 16 unless @user.valid? 17 flash.now[:alert] = @user.errors.full_messages 18 render :new and return 19 end 20 session["devise.regist_data"] = {user: @user.attributes} 21 session["devise.regist_data"][:user]["password"] = params[:user][:password] 22 @cellphone = @user.build_cellphone 23 render :new_cellphone 24 end 25 26 def create_cellphone 27 @user = User.new(session["devise.regist_data"]["user"]) 28 @cellphone = Cellphone.new(cellphone_params) 29 unless @cellphone.valid? 30 flash.now[:alert] = @cellphone.errors.full_messages 31 render :new_cellphone and return 32 end 33 @user.build_cellphone(@cellphone.attributes) 34 session["cellphone"] = @cellphone.attributes 35 @address = @user.build_address 36 render :new_address 37 end 38 39 def create_address 40 @user = User.new(session["devise.regist_data"]["user"]) 41 @cellphone = Cellphone.new(session["cellphone"]) 42 @address = Address.new(address_params) 43 unless @address.valid? 44 flash.now[:alert] = @address.errors.full_messages 45 render :new_address and return 46 end 47 @user.build_cellphone(@cellphone.attributes) 48 @user.build_address(@address.attributes) 49 session["address"] = @address.attributes 50 @card = @user.build_card 51 render :new_card 52 end 53 54 55 def create_card 56 @user = User.new(session["devise.regist_data"]["user"]) 57 @cellphone = Cellphone.new(session["cellphone"]) 58 @address = Address.new(session["address"]) 59 @card = Card.new(card_params) 60 unless @card.valid? 61 flash.now[:alert] = @card.errors.full_messages 62 render :new_card and return 63 end 64 @user.build_cellphone(@cellphone.attributes) 65 @user.build_address(@address.attributes) 66 @user.build_card(@card.attributes) 67 @user.save 68 sign_in(:user, @user) 69 end 70 71 # GET /resource/edit 72 # def edit 73 # super 74 # end 75 76 # PUT /resource 77 # def update 78 # super 79 # end 80 81 # DELETE /resource 82 # def destroy 83 # super 84 # end 85 86 # GET /resource/cancel 87 # Forces the session data which is usually expired after sign 88 # in to be expired now. This is useful if the user wants to 89 # cancel oauth signing in/up in the middle of the process, 90 # removing all OAuth session data. 91 # def cancel 92 # super 93 # end 94 95 protected 96 97 # If you have extra params to permit, append them to the sanitizer. 98 def configure_sign_up_params 99 devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute]) 100 end 101 102 def cellphone_params 103 params.require(:cellphone).permit(:number) 104 end 105 106 def address_params 107 params.require(:address).permit(:zip_code, :prefecture, :city, :address, :building, :phone_tell) 108 end 109 110 def card_params 111 params.require(:card).permit(:number, :validated_date_year, :validated_date_month, :security_number) 112 end 113 114 115 116 # If you have extra params to permit, append them to the sanitizer. 117 # def configure_account_update_params 118 # devise_parameter_sanitizer.permit(:account_update, keys: [:attribute]) 119 # end 120 121 # The path used after sign up. 122 # def after_sign_up_path_for(resource) 123 # super(resource) 124 # end 125 126 # The path used after sign up for inactive accounts. 127 # def after_inactive_sign_up_path_for(resource) 128 # super(resource) 129 # end 130end 131

#rails_helper.rb

ruby

1# This file is copied to spec/ when you run 'rails generate rspec:install' 2require 'spec_helper' 3ENV['RAILS_ENV'] ||= 'test' 4 5require File.expand_path('../config/environment', __dir__) 6 7# Prevent database truncation if the environment is production 8abort("The Rails environment is running in production mode!") if Rails.env.production? 9require 'rspec/rails' 10# Add additional requires below this line. Rails is not loaded until this point! 11 12# Requires supporting ruby files with custom matchers and macros, etc, in 13# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 14# run as spec files by default. This means that files in spec/support that end 15# in _spec.rb will both be required and run as specs, causing the specs to be 16# run twice. It is recommended that you do not name files matching this glob to 17# end with _spec.rb. You can configure this pattern with the --pattern 18# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 19# 20# The following line is provided for convenience purposes. It has the downside 21# of increasing the boot-up time by auto-requiring all files in the support 22# directory. Alternatively, in the individual `*_spec.rb` files, manually 23# require only the support files necessary. 24# 25# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } 26 27# Checks for pending migrations and applies them before tests are run. 28# If you are not using ActiveRecord, you can remove these lines. 29begin 30 ActiveRecord::Migration.maintain_test_schema! 31rescue ActiveRecord::PendingMigrationError => e 32 puts e.to_s.strip 33 exit 1 34end 35RSpec.configure do |config| 36 # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 37 config.fixture_path = "#{::Rails.root}/spec/fixtures" 38 config.include FactoryBot::Syntax::Methods 39 # config.include Devise::TestHelpers, type: :controller 40 config.include Devise::Test::ControllerHelpers, type: :controller 41 # If you're not using ActiveRecord, or you'd prefer not to run each of your 42 # examples within a transaction, remove the following line or assign false 43 # instead of true. 44 config.use_transactional_fixtures = true 45 46 # RSpec Rails can automatically mix in different behaviours to your tests 47 # based on their file location, for example enabling you to call `get` and 48 # `post` in specs under `spec/controllers`. 49 # 50 # You can disable this behaviour by removing the line below, and instead 51 # explicitly tag your specs with their type, e.g.: 52 # 53 # RSpec.describe UsersController, :type => :controller do 54 # # ... 55 # end 56 # 57 # The different available types are documented in the features, such as in 58 # https://relishapp.com/rspec/rspec-rails/docs 59 config.infer_spec_type_from_file_location! 60 61 # Filter lines from Rails gems in backtraces. 62 config.filter_rails_from_backtrace! 63 # arbitrary gems may also be filtered via: 64 # config.filter_gems_from_backtrace("gem name") 65end 66

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

rb

Users::RegistrationsController#create_card

def create_card
@user = User.new(session["devise.regist_data"]["user"])
@cellphone = Cellphone.new(session["cellphone"])
@address = Address.new(session["address"])
@card = Card.new(card_params)
unless @card.valid?
flash.now[:alert] = @card.errors.full_messages
render :new_card and return
end
@user.build_cellphone(@cellphone.attributes)
@user.build_address(@address.attributes)
@user.build_card(@card.attributes)
@user.save
sign_in(:user, @user)
end

そもそもコントローラでリダイレクトするように書かれていないように見受けられます。 `sign_in(:user, @user)`部分でリダイレクトされているのであればその部分を追記してください。 また、このコードで実際に画面で動かした時は正しく動作していますか?

投稿2020/02/13 01:41

編集2020/02/13 01:43
Mugheart

総合スコア2344

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

shuya-tamaru

2020/02/13 15:56

ありがとうございます! 開発環境では問題なく正しく動作してます! いただいた回答を参考に、sign_in @userを入れたことで、とりあえず一歩進んだような気はします。 現状、2つのテストが同様のエラー RuntimeError: Could not find a valid mapping for になったので、今度はこれを解決していこうと思います!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問