10

我正在开发一个使用 CanCan 授权我的资源的 Rails 项目。当用户未登录并尝试提交“谈话”(通过 ajax 表单提交)时,CanCan 正确地引发 401{"status":"error","message":"You must be logged in to do that!"}作为响应(我已使用 firebug 在浏览器中验证了这一点)。但是,在我的测试中得到 302 响应代码而不是 401:

class TalksController < ApplicationController
  authorize_resource

  def create
    @talk = current_user.talks.build(params[:talk])

    respond_to do |format|
      if @talk.save
        response = { :redirect => talk_path(@talk) }
        format.html { redirect_to @talk, notice: 'Talk was successfully created.' }
        format.json { render json: response, status: :created,  }
      else
        format.html { render action: "new" }
        format.json { render json: @talk.errors, status: :unprocessable_entity }
      end
    end
  end
end

talk_controller_spec.rb:

describe TalksController do
  describe "POST create" do
    context "when not signed in" do
      it "should not assign talk" do
        post :create
        assigns[:talk].should be_nil
      end
      it "should respond with a 401" do
        post :create
        response.response_code.should == 401
      end
    end
  end
end

这里包含的第一个例子是成功的(assigns[:talk] 没有被赋值),但第二个例子不是:

1) TalksController POST create when not signed in should respond with a 401
     Failure/Error: response.response_code.should == 401
       expected: 401
            got: 302 (using ==)
     # ./spec/controllers/talks_controller_spec.rb:53:in `block (4 levels) in <top (required)>'

我不确定到底发生了什么。有没有办法可以测试返回给浏览器的实际响应代码?还是我可以测试授权的更好方法?

4

1 回答 1

9

事实证明,我的项目使用以下函数从 CanCan 中解救了授权异常。因为该函数仅在请求为 ajax 时引发 401(否则重定向),我在浏览器中得到 401,但不是我的测试。

# Handle authorization exceptions
rescue_from CanCan::AccessDenied do |exception|
  if request.xhr?
    if signed_in?
      render json: {:status => :error, :message => "You don't have permission to #{exception.action} #{exception.subject.class.to_s.pluralize}"}, :status => 403
    else
      render json: {:status => :error, :message => "You must be logged in to do that!"}, :status => 401
    end
  else
    render :file => "public/401.html", :status => :unauthorized
  end
end

感谢zetetic建议我检查我的测试日志,因为这揭示了请求的差异。

于 2011-10-11T02:33:31.537 回答