如何使用RSpec测试CanCan失败授权的响应代码?

时间:2011-10-06 22:41:56

标签: rspec controller cancan rspec-rails

我正在开发一个rails项目,我在其中使用CanCan来授权我的资源。当用户未登录并尝试提交“谈话”(通过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

talks_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

此处包含的第一个示例是成功的(分配[: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)>'

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

1 个答案:

答案 0 :(得分:8)

事实证明,我的项目使用以下功能从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建议我检查我的测试日志,因为这显示了请求的不同。