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

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回答

1495閲覧

rspecによるdeviseを用いた新規登録画面のcontrollerの単体テストの際のエラー(undefined method `validatable?' for nil:NilClass)

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/06 16:28

前提・実現したいこと

Ruby on rails を用いてdeviseを用いた新規登録機能を実装
newアクションで新規登録画面に遷移し、new.html.hamlが表示されるかのcontrollerの単体テストを行おうとしたが、
以下のエラーメッセージ(NoMethodError:undefined method `validatable?' for nil:NilClass)が発生しました。
ググってみたのですが解決できず、初心者で基本的なことかもしれず申し訳ないのですが、ご教授いただければと思います。

発生している問題・エラーメッセージ

Users::RegistrationsController GET #new renders the :new template (FAILED - 1) Failures: 1) Users::RegistrationsController GET #new renders the :new template Failure/Error: get :new NoMethodError: undefined method `validatable?' for nil:NilClass # ./spec/controllers/users/registrations_controller_spec.rb:7:in `block (3 levels) in <top (required)>' Finished in 0.01058 seconds (files took 4.25 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/controllers/users/registrations_controller_spec.rb:6 # Users::RegistrationsController GET #new renders the :new template

該当のソースコード

spec/controllers/users/registrations_controller_spec.rb

ruby

1 2require 'rails_helper' 3 4describe Users::RegistrationsController, type: :controller do 5 6 describe 'GET #new' do 7 it "renders the :new template" do 8 get :new 9 expect(response).to render_template :new 10 end 11 end 12end

app/controller/users/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

spec/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 # If you're not using ActiveRecord, or you'd prefer not to run each of your 40 # examples within a transaction, remove the following line or assign false 41 # instead of true. 42 config.use_transactional_fixtures = true 43 44 # RSpec Rails can automatically mix in different behaviours to your tests 45 # based on their file location, for example enabling you to call `get` and 46 # `post` in specs under `spec/controllers`. 47 # 48 # You can disable this behaviour by removing the line below, and instead 49 # explicitly tag your specs with their type, e.g.: 50 # 51 # RSpec.describe UsersController, :type => :controller do 52 # # ... 53 # end 54 # 55 # The different available types are documented in the features, such as in 56 # https://relishapp.com/rspec/rspec-rails/docs 57 config.infer_spec_type_from_file_location! 58 59 # Filter lines from Rails gems in backtraces. 60 config.filter_rails_from_backtrace! 61 # arbitrary gems may also be filtered via: 62 # config.filter_gems_from_backtrace("gem name") 63end 64

config/routes.rb

ruby

1Rails.application.routes.draw do 2 devise_for :users, controllers: { 3 registrations: 'users/registrations', 4 } 5 devise_scope :user do 6 get 'cellphones', to: 'users/registrations#new_cellphone' 7 post 'cellphones', to: 'users/registrations#create_cellphone' 8 get 'addresses', to: 'users/registrations#new_address' 9 post 'addresses', to: 'users/registrations#create_address' 10 get 'cards', to: 'users/registrations#new_card' 11 post 'cards', to: 'users/registrations#create_card' 12 end 13 root to: "items#index" 14 resources :items 15 resources :credit_cards, only: [:index,:new,:show] 16end 17

補足情報(FW/ツールのバージョンなど)

ruby '2.5.1'
'rails', '~> 5.2.3'

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

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

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

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

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

guest

回答1

0

ベストアンサー

deviseのテストコードですが参考になると思います。
test/controllers/custom_registrations_controller_test.rb

投稿2020/02/06 22:23

asm

総合スコア15147

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

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

shuya-tamaru

2020/02/07 14:58

参考資料を元に @request.env["devise.mapping"] = Devise.mappings[:user] の追加と rails_helper.rb に config.include Devise::Test::ControllerHelpers, type: :controllerを追加したらerror消えました! 要因は今から調べてみようと思います! ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問