Respond with Unauthorized Status (401) with Rails 4

Given the following Rails 4.2 controller:

class Api::UsersController < ApplicationController def index respond_to do |format| format.html do flash[:error] = 'Access denied' redirect_to root_url end format.json do render json: {}, status: :unauthorised end end end end 

When with RSpec 3, I try to call this index action and expect that status 401 will always have status 200.

The only time I got 401 was to replace the contents of index action of head 401 , but I would like to respond with error 401, and also create a "nice" body, for example { error: 401, message: 'Unauthorised' } .

Why is status: :unauthorised ignored?

+8
ruby ruby-on-rails ruby-on-rails-4
source share
3 answers

I had to replace my controller with the following:

 class Api::UsersController < ApplicationController def index respond_to do |format| format.html do flash[:error] = 'Access denied' redirect_to root_url end format.json do self.status = :unauthorized self.response_body = { error: 'Access denied' }.to_json end end end end 

Using render does not interfere with the execution of the called action. Using head :unauthorized returns the correct status code, but with an empty body.

With self.status and self.response_body it works fine.

You can see the source code of my gem where I had this problem: https://github.com/YourCursus/fortress

+5
source share

Use the error code instead of the name: render json: {}, status: 401

+6
source share

Replace unauthorised with unauthorized

0
source share

All Articles