What does line do? `:@request.env["devise.mapping"] = Devise.mappings[:user] `

1.5k Views Asked by At

I am reviewing rspec tests and trying to understand what the following code does.

  before do
    @request.env["devise.mapping"] = Devise.mappings[:user]
    setup_controller_for_warden
    @user = create(:user)  
  end
1

There are 1 best solutions below

0
On

Devise documentation suggests adding the @request.env["devise.mapping"] = Devise.mappings[:user] when you are testing a Devise controller or a controller that inherits from a Devise controller:

If you are testing Devise internal controllers or a controller that inherits from Devise's, you need to tell Devise which mapping should be used before a request. This is necessary because Devise gets this information from the router, but since controller tests do not pass through the router, it needs to be stated explicitly. 

And also the gem itself warns you about it in some cases:

Could not find devise mapping for path #{request.fullpath.inspect}.
This may happen for two reasons:

1) You forgot to wrap your route inside the scope block. For example:

  devise_scope :user do
    get "/some/route" => "some_devise_controller"
  end

2) You are testing a Devise controller bypassing the router.
   If so, you can explicitly tell Devise which mapping to use:

   @request.env["devise.mapping"] = Devise.mappings[:user]