0

Having a weird issue with rails (5.0.5) right now. I know the render and return is running because I can use binding.pry to step in. It should be returning with a status code forbidden however when I run my test it returns with status code 204 no content instead.

# we already know this user has permission for org_claim_codes#create but we need to check they are part of this org
unless @current_user.orgs.map(&:id).include?(new_org_claim_code_params[:org_id].to_i) || @current_user.has_permission?('*', '*')
  render json: { errors: ['user not authorized']}, status: :forbidden && return
end

In my test I expect the status to be forbidden

expect(response).to have_http_status(:forbidden)

but i get an error stating

Failures:

1) OrgClaimCodesController#create permissions does not allow a user without permission weather or not they are in the org
 Failure/Error: expect(response).to have_http_status(:forbidden)
   expected the response to have status code :forbidden (403) but it was :no_content (204)
 # ./spec/controllers/org_claim_codes_controller_spec.rb:49:in `block (4 levels) in <top (required)>'

Finished in 0.3044 seconds (files took 2.26 seconds to load)

1 example, 1 failure

Full controller code

# create new claim code based on org_id
def create
# we already know this user has permission for org_claim_codes#create but we need to check they are part of this org
unless @current_user.orgs.map(&:id).include?(new_org_claim_code_params[:org_id].to_i) || @current_user.has_permission?('*', '*')
  render json: { errors: ['user not authorized']}, status: :forbidden && return
end

claim = OrgClaimCode.new(new_org_claim_code_params)
if claim.save
  render json: claim
else
  render json: { errors: claim.errors.full_messages }, status: :unprocessable_entity
end

end

full test

it 'does not allow a user without permission weather or not they are in the org' do
    current_user
    expect do
      post :create, params: { org_claim_codes: { org_id: create(:org).id } } # a different org than we set perms for
    end.to change(OrgClaimCode, :count).by(0)

    expect(response).to have_http_status(:forbidden)
  end

2 Answers2

0

In controller rewrite:

render json: { errors: ['user not authorized']}, status: :forbidden && return

TO

render json: { errors: ['user not authorized']}, status: :forbidden and return

Explanation:

&& has higher precedence than and. Besides, in your code render json: { errors: ['user not authorized']}, status: :forbidden is true, so it just executes this and do not goes for return.

Check it out, it explains everything.

Cheers!

rony36
  • 3,277
  • 1
  • 30
  • 42
0

You can remove the && return or and return completely and it should work. Also 403 is the error code for forbidden.

SickLickWill
  • 196
  • 1
  • 6