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

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

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

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

RSpec

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

Ruby on Rails

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

Q&A

2回答

1639閲覧

【Rails】RSpecによるコントローラーの単体テストを実行すると、undefinedエラーが出力される

yxmr_8940

総合スコア0

Devise

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

RSpec

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

Ruby on Rails

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

0グッド

0クリップ

投稿2021/06/01 09:16

前提・実現したいこと

Railsの初学者です。
Deviseを導入した状態で、RSpecによるコントローラーの単体テストを実行したところ、
「undefined local variable or method login_user' for #<RSpec::ExampleGroups::RunsController::GETNew:0x00007fcc2aadc750> # ./spec/requests/runs_spec.rb:40:in block (3 levels) in <top (required)>'

というエラーが出力され、controller_macros.rbで定義したlogin_userメソッドが使用できない。

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

エラーメッセージ

Failures: 1) RunsController GET #new ログインユーザーであればnewアクションにリクエストすると適切にレスポンスが返される Failure/Error: login_user NameError: undefined local variable or method `login_user' for #<RSpec::ExampleGroups::RunsController::GETNew:0x00007fcc2aadc750> # ./spec/requests/runs_spec.rb:40:in `block (3 levels) in <top (required)>'

該当のソースコード

1 rails_helper.rb # This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' require 'devise' require_relative 'support/controller_macros' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../config/environment', __dir__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e puts e.to_s.strip exit 1 end RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # You can uncomment this line to turn off ActiveRecord support entirely. # config.use_active_record = false # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, type: :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") config.include Devise::Test::ControllerHelpers, :type => :controller config.extend ControllerMacros, :type => :controller end
2 support/controller_macros.rb module ControllerMacros def login_admin before(:each) do @request.env["devise.mapping"] = Devise.mappings[:admin] admin = FactoryBot.create(:admin) sign_in :user, sdmin end end def login_user before(:each) do user = FactoryBot.create(:user) user.confirm! sign_in user end end end
3 spec/request/runs_spec.rb require 'rails_helper' RSpec.describe RunsController, type: :request do before do @user = FactoryBot.create(:user) @run = FactoryBot.create(:run) end describe 'GET #index' do it 'indexアクションにリクエストすると正常にレスポンスが返ってくる' do get root_path expect(response.status).to eq 200 end it 'indexアクションにリクエストするとレスポンスに投稿のタイトルが存在する' do get root_path expect(response.body).to include(@run.title) end it 'indexアクションにリクエストするとレスポンスに投稿の画像が存在する' do get root_path expect(response.body).to include('test_image.png') end it 'indexアクションにリクエストするとレスポンスに投稿したユーザーの名前が存在する' do get root_path expect(response.body).to include(@run.user.nickname) end it 'indexアクションにリクエストするとレスポンスにログインボタンが存在する' do get root_path expect(response.body).to include("ログイン") end it 'indexアクションにリクエストするとレスポンスに新規登録ボタンが存在する' do get root_path expect(response.body).to include("新規登録") end end describe 'GET #new' do it 'ログインユーザーでないとnewアクションにリクエストするとリダイレクトされる' do get new_run_path expect(response.status).to eq 302 end it 'ログインユーザーであればnewアクションにリクエストすると適切にレスポンスが返される' do login_user get new_run_path expect(response.status).to eq 200 end end end

試したこと

①コントローラーの単体テストコードを行うところ、authenticate_user!メソッドにより、未ログインのユーザーはリダイレクトされ、ログイン済みのユーザーは新規投稿ページ(newアクション)にアクセスできることを確認したい。
②そのためControllerMacrosモジュールを作成し、rails_helper.rbに読み込まれるように記述した。
③しかし、上記のとおり、ControllerMacrosモジュール内に記述したlogin_userメソッドなんて定義されていないと出力される。
④以下のサイト様を参照させていただきました。
https://hirocorpblog.com/post-112/#index_id9
⑤同様のケースを探しましたが、解決策が見つかりませんでした。
⑥何卒、ご教示のほどよろしくお願いいたします。

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

Ruby 2.6.5
Ruby on Rails 6.0.0
devise 4.7.3
RSpec 4.0.0

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

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

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

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

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

guest

回答2

0

他人のサイトを参考にする場合は一度、公式で情報を確かめた方がよいです。
今回の場合

いつも通り、githubを見にいきましょう!
Minitestのコントローラーと統合テスト、コントローラーspecでのやり方が載っているようです。

How To: Test controllers with Rails (and RSpec)
https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-(and-RSpec)

ネタ元が明らかになっているので見に行くと

config.include Devise::Test::IntegrationHelpers, type: :request

が、提示されたソースに追加されています。
筆者がコントローラーテストのみで済ませていたのか、公式が後から追加したのかは不明ですが
現状としては公式に合わせ追加しとく方がよいでしょう。

また、

require 'rspec/rails'
​# note: require 'devise' after require 'rspec/rails'
require 'devise'

と、注意がされているのでrequire 'rspec/rails'しておいた方が無難です。


使い方ですが
login_userの代わりにsign_in(@user)としてください

投稿2021/06/10 08:08

編集2021/06/10 08:20
asm

総合スコア15147

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

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

0

requireはしてますが、module ControllerMacros を include も extend もしていないので、そのなかの methodは取り込まれていません。
module ... end を外すとうまく行くかも。
ただ、、、、
中身が before(:each) になってますが、これで動くのか私にはわかりません。

投稿2021/06/01 10:54

winterboum

総合スコア23284

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

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

yxmr_8940

2021/06/01 23:57

ご回答大変ありがとうございます! module ControllerMacrosについては、rails_helper.rbファイルに、 ・config.include Devise::Test::ControllerHelpers, :type => :controller ・config.extend ControllerMacros, :type => :controller とincludeとextendしているのですが、うまくいきません。 ご回答を参考にチャレンジしてみます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問