Rspec統合テストのDeviseマッピングエラー

Web技術メモ

はじめに

開発中のWebアプリに統合テスト(RSpec の request spec)を追加しました。

ところが実行すると、エラーメッセージが出てテストが通りませんでした。

発生したエラー

RuntimeError: Could not find a valid mapping for #<User ...>

原因

Devise のマッピング(scope)が未ロードだったため。

Rails8ではルーティングが遅延読み込み(lazy load)されるため、devise_for :users が定義するマッピングが sign_in 実行時点でまだ読み込まれていない。

対策

テスト全体で、一度だけ先読みするようにコードを追加。

# ✅OK: spec/support/devise_routes.rb
RSpec.configure do |config|
  config.before(:suite) do
    Rails.application.routes_reloader.execute_unless_loaded
  end
end

rails_helper.rb で Devise を読み込む&ヘルパーを有効化

require 'rspec/rails'
require 'devise'

RSpec.configure do |config|
  config.include Devise::Test::IntegrationHelpers, type: :request
end

以下の行を有効化

Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }

さいごに

これで、無事にテストが通りました。

テスト実行結果:グリーン

参考

Rails 8: test helpers do not work ?? Issue #5705 ?? heartcombo/devise
Environment Ruby 3.3.2 Rails main (8.0.0.alpha) Devise 4.9.4 Steps to reproduce Run the following bash commands (tested ...

タイトルとURLをコピーしました