Overview
Rails8でRspecとDeviseを使ってテストするとエラーが出るようになった。
それをモンキーパッチ的に解消したので共有しますー。
エラー
RuntimeError:
Could not find a valid mapping for #<User id...
解決策
touch config/initializers/devise_rails8_patch.rb
devise_rails8_patch.rb
require 'devise'
Devise # make sure it's already loaded
module Devise
def self.mappings
# Starting from Rails 8.0, routes are lazy-loaded by default in test and development environments.
# However, Devise's mappings are built during the routes loading phase.
# To ensure it works correctly, we need to load the routes first before accessing @@mappings.
Rails.application.try(:reload_routes_unless_loaded)
@@mappings
end
end
$ bundle exec rspec
Deviseの公式リポジトリでも話題に上がってる内容みたいで、早速PRが作成されていてすでにマージされている内容みたいですね。
Devise5がリリースされたら解消されるみたいですが、最新は4.9.4なので、PRの内容を拝借して一時的にエラーを解消してみました。
Converting this PR to this patch in a config/initializers/devise_rails8_patch.rb file seems to let me get going with Rails 8 and devise 4.9.4.
https://github.com/heartcombo/devise/pull/5728#issuecomment-2539418211