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

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

新規登録して質問してみよう
ただいま回答率
85.50%
Ruby on Rails 5

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

Q&A

1回答

1364閲覧

rails testにてundefined method `id' for nil:NilClassエラーが解決できない

kinu221

総合スコア26

Ruby on Rails 5

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

1グッド

0クリップ

投稿2018/03/21 08:25

編集2022/01/12 10:55

[現象]
rails testを実行するとundefined method `id' for nil:NilClassエラーが発生する。
下名では解決できませんでしたので、ご教授願います。

[環境]
cloud9,
Rails 5.1.4

Error:
UsersProfileTest#test_profile_display:
ActionView::Template::Error: undefined method id' for nil:NilClass app/views/likes/_like.html.erb:1:in _app_views_likes__like_html_erb___114985059599241592_62177660'
app/views/microposts/_micropost.html.erb:16:in _app_views_microposts__micropost_html_erb__3344069742097572585_62280280' app/views/users/show.html.erb:20:in _app_views_users_show_html_erb___489431433523421794_53681160'
test/integration/users_profile_test.rb:11:in `block in class:UsersProfileTest'

bin/rails test test/integration/users_profile_test.rb:10

[ソースコード]

---_like.html.erb--- <% if micropost.like_user(current_user.id) %> <%= button_to micropost_like_path(likes, micropost_id: micropost.id), method: :delete, id: "like-button", remote: true do %> <%= image_tag("icon_red_heard.png") %> <span> <%= micropost.likes_count %> </span> <% end %> <% else %> <%= button_to micropost_likes_path(micropost),id: "like-button", remote: true do %> <%= image_tag("icon_red_heart.png") %> <span> <%= micropost.likes_count %> </span> <% end %> <% end %>
---_micropost.html.erb--- <li id="micropost-<%= micropost.id %>"> <%= link_to gravatar_for(micropost.user, size: 50), micropost.user %> <span class="user"><%= link_to micropost.user.name, micropost.user %></span> <span class="content"> <%= micropost.content %> <%= image_tag micropost.picture.url if micropost.picture? %> </span> <span class="timestamp"> Posted <%= time_ago_in_words(micropost.created_at) %> ago. <% if current_user?(micropost.user) %> <%= link_to "delete", micropost, method: :delete, data: { confirm: "You sure?" } %> <% end %> </span> <!--like拡張機能--> <%= render partial: 'likes/like', locals: { micropost: micropost, likes: @likes } %> </li>
---show.html.erb--- <% provide(:title, @user.name) %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <h1> <%= gravatar_for @user %> <%= @user.name %> </h1> </section> <section class="stats"> <%= render 'shared/stats' %> </section> </aside> <div class="col-md-8"> <%= render 'follow_form' if logged_in? %> <% if @user.microposts.any? %> <h3>Microposts (<%= @user.microposts.count %>)</h3> <ol class="microposts"> <%= render @microposts %> </ol> <%= will_paginate @microposts %> <% end %> </div> </div>
---users_profile_test.rb--- require 'test_helper' class UsersProfileTest < ActionDispatch::IntegrationTest include ApplicationHelper def setup @user = users(:michael) end test "profile display" do get user_path(@user) assert_template 'users/show' assert_select 'title', full_title(@user.name) assert_select 'h1', text: @user.name assert_select 'h1>img.gravatar' assert_match @user.microposts.count.to_s, response.body assert_select 'div.pagination' @user.microposts.paginate(page: 1).each do |micropost| assert_match micropost.content, response.body end end end

ruby

1--sessions_controller.rb-- 2class SessionsController < ApplicationController 3 4 def new 5 end 6 7 def create 8 user = User.find_by(email: params[:session][:email].downcase) 9 if user && user.authenticate(params[:session][:password]) 10 if user.activated? 11 log_in user 12 params[:session][:remember_me] == '1' ? remember(user) : forget(user) 13 redirect_back_or user 14 else 15 message = "Account not activated. " 16 message += "Check your email for the activation link." 17 flash[:warning] = message 18 redirect_to root_url 19 end 20 else 21 flash.now[:danger] = 'Invalid email/password combination' 22 render 'new' 23 end 24 end 25 26 def destroy 27 log_out if logged_in? 28 redirect_to root_url 29 end 30end

ruby

1--sessions_controller_test.rb-- 2require 'test_helper' 3 4class SessionsControllerTest < ActionDispatch::IntegrationTest 5 test "should get new" do 6 get login_path 7 assert_response :success 8 end 9 10end

ruby

1--users_login_test.rb-- 2require 'test_helper' 3 4class UsersLoginTest < ActionDispatch::IntegrationTest 5 def setup 6 @user = users(:michael) 7 end 8 9 test "login with invalid information" do 10 get login_path 11 assert_template 'sessions/new' 12 post login_path, params: { session: { email: "", password: "" } } 13 assert_template 'sessions/new' 14 assert_not flash.empty? 15 get root_path 16 assert flash.empty? 17 end 18 19 test "login with valid information followed by logout" do 20 get login_path 21 post login_path, params: { session: { email: @user.email, 22 password: 'password' } } 23 assert is_logged_in? 24 assert_redirected_to @user 25 follow_redirect! 26 assert_template 'users/show' 27 assert_select "a[href=?]", login_path, count: 0 28 assert_select "a[href=?]", logout_path 29 assert_select "a[href=?]", user_path(@user) 30 31 delete logout_path 32 assert_not is_logged_in? 33 assert_redirected_to root_url 34 # 2番目のウィンドウでログアウトをクリックするユーザーをシミュレートする 35 delete logout_path 36 follow_redirect! 37 assert_select "a[href=?]", login_path 38 assert_select "a[href=?]", logout_path, count: 0 39 assert_select "a[href=?]", user_path(@user), count: 0 40 end 41 42 test "login with remembering" do 43 log_in_as(@user, remember_me: '1') 44 assert_not_empty cookies['remember_token'] 45 end 46 47 test "login without remembering" do 48 # クッキーを保存してログイン 49 log_in_as(@user, remember_me: '1') 50 delete logout_path 51 # クッキーを削除してログイン 52 log_in_as(@user, remember_me: '0') 53 assert_empty cookies['remember_token'] 54 end 55end 56

[試したこと]
・ネットで調べて、undefined method `id'or nil:NilClassエラーはユーザー登録がされていないため表示されているというQ&Aを見たので、ユーザーのsignupを行なったがトラブルシュートできず。
・エラーが出ていると思われるソースコードのサンプルコードと照合。

退会済みユーザー👍を押しています

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

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

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

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

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

guest

回答1

0

current_usernil を返しているのが原因ですね。
これはログインされていないことを意味します。
テストにおいても,ログインに相当するコードを書いてやらなければ,ログインが前提のアクションのテストはできません。

で,テストコードの中にログインにあたるコードをどのように書くかですが,これは認証の仕組みによって異なります。

devise とか sorcery を使っているなら,それに沿った書き方があります。それぞれのライブラリーのドキュメントにたぶん書いてあります。
sorcery の場合は私は少しだけ分かりますが,devise は分かりません。

投稿2018/03/21 08:40

scivola

総合スコア2108

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

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

kinu221

2018/03/30 13:11

ご回答ありがとうございます。Deviseを使っていなかったので、Deviseをインストールしようとしましたが、Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=developmentエラーが発生しています。migrateの失敗だと思うのですが、ネットで調べても解決しないのでアドバイスを御願い致します。
scivola

2018/03/31 01:08

いえ,devise を使っていないならテストを通すために入れる必要はありません。 現状で既に認証(ログイン)の仕組みはあるんですよね? それに則ってテストを書く必要がある,という話です。 認証は今どうやっているのですか?
kinu221

2018/03/31 11:02

そうでしたか。認証(ログイン)の仕組みはloginメソッドを使用して作っています。ソースコードを質問内容に記載しました。
scivola

2018/04/01 01:01

UsersLoginTest の "login with valid information followed by logout" はパスしていますか。 しているなら,その最初の 2 行,つまり, get login_path post login_path, params: { 云々 } の部分を,件のテストの先頭に追加してやればいいのではないかと思います。
kinu221

2018/04/07 03:46

解決致しました。ここまでお付き合いいただきありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問