当明确告知返回401时,Rails返回204

时间:2017-08-29 02:58:55

标签: ruby-on-rails rspec

现在有一个奇怪的rails(5.0.5)问题。我知道渲染和返回正在运行,因为我可以使用binding.pry介入。它应该返回状态代码为禁止但是当我运行我的测试时,它返回状态代码204而不是内容。

# 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

在我的测试中,我希望状态被禁止

expect(response).to have_http_status(:forbidden)

但我收到错误说明

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例,1次失败

完整控制器代码

# 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

完整测试

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 个答案:

答案 0 :(得分:0)

在控制器重写中:

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

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

<强>解释

  

&&的{​​{3}}高于and。此外,在您的代码中render json: { errors: ['user not authorized']}, status: :forbiddentrue,因此它只是执行此操作而不是return

precedence,它解释了一切。

干杯!

答案 1 :(得分:0)

您可以完全删除&& returnand return,它应该可以使用。 403也是禁止的错误代码。