1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rail8+Devise+Rspecで出るRuntimeErrorを解消する

Last updated at Posted at 2025-02-09

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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?