Helper Devise: could not find the `Warden::Proxy` instance on request environment
Based on this SO answer you need to include the Devise::Test::ControllerHelpers
module in your controller specs. Add the following to your rails_helper:
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, type: :controller
end
Add
config.include Devise::Test::ControllerHelpers, type: :controller
in your rails_helper.rb file.
It can happen when you call Devise methods, like current_user
, in code being managed by action cable. like a background job to render comment or something else.
You may resolve it by doing something like the following in your controller. It propagates warden
to the the @env['warden'] variable so that Devise can use it:
def create
@product = Product.find(comment_params[:product_id])
@comment = @product.comments.build(comment_params)
@comment.save!
gon.comment_id = @comment.id
gon.comment_user_id = @comment.user_id
ActionCable.server.broadcast "chat", comment: render_comment
render :create, layout: false
end
def render_comment
CommentsController.renderer.instance_variable_set(
:@env, {
"HTTP_HOST"=>"localhost:3000",
"HTTPS"=>"off",
"REQUEST_METHOD"=>"GET",
"SCRIPT_NAME"=>"",
"warden" => warden
}
)
CommentsController.render(
partial: 'comments/comment_detail',
locals: {
product: @product,
comment: @comment
}
)
end
This will help you resolve the warden issue, if you have used Devise's current_user
in that partial, it will give you the commentor user (as it should since that user initiated the rendering of partial).
Now to solve this, if you have a front end framework you might need to fetch the current user from cookies in order to restrict some actions like edit/delete. but if you are working in pure rails the solution I came across is that you have to make a hidden field in the dom having current users id, and you will fetch that id for comparison in a script. you might need to access rails variables in javascript, for that you can use GON gem.
I know this answer might contain much more than asked but I've searched alot and no where I found a satisfactory solution to this problem, feel free to discuss.