Fixing the “Could not find a valid mapping” Error in Rails 8 Tests
Jess Alejo

Jess Alejo @jessalejo

About: I write code

Joined:
Mar 14, 2022

Fixing the “Could not find a valid mapping” Error in Rails 8 Tests

Publish Date: Jun 24
1 0

While writing RSpec tests for a model that references User, I encountered this error:

RuntimeError:
  Could not find a valid mapping for #<User ...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!

Comments 0 total

    Add comment