ZedTuX
ZedTuX

Reputation: 3027

Respond with a status unauthorised (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 to have the status 401 I always have the status 200.

The only moment where I got the 401 is to replace the index action content with head 401 but I would like to respond with the error 401 and also build a "nice" body like { error: 401, message: 'Unauthorised' }.

Why is the status: :unauthorised ignored ?

Upvotes: 19

Views: 23232

Answers (3)

ZedTuX
ZedTuX

Reputation: 3027

I had to replace my controller with this 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 is not preventing the called action to be executed. Using head :unauthorized is returning the right status code but with a blank body.

With self.status and self.response_body it's working perfectly.

You can see have a look to the source code my gem where I had this issue here: https://github.com/YourCursus/fortress

Upvotes: 7

Alex Tonkonozhenko
Alex Tonkonozhenko

Reputation: 1574

Use error code instead of it's name: render json: {}, status: 401

Upvotes: 22

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Replace unauthorised by unauthorized

Upvotes: 4

Related Questions