While writing RSpec tests for a model that references User, I encountered this error:
RuntimeError:
Could not find a valid mapping for #<User ...
At first glance, it seemed like a Devise misconfiguration. But after digging deeper, I found the root cause: Rails 8 now lazy loads routes by default, and this behavior breaks Devise's internal logic during test runs if the routes haven't been loaded yet.
The Fix
To solve it, simply add this snippet in your spec/rails_helper.rb:
ActiveSupport.on_load(:action_mailer) do
Rails.application.reload_routes_unless_loaded
end
This ensures routes are loaded before tests relying on Devise or User mappings run.
Why This Happens
Devise needs access to routes to resolve model mappings (like for authentication or email delivery). Since Rails 8 defers route loading for performance, Devise can’t find the route it needs during test boot, unless you force it.
Reference
Big thanks to Alvin Crespo for documenting this!
Top comments (0)