我正在开发一个使用 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)>'
我不确定到底发生了什么。有没有办法可以测试返回给浏览器的实际响应代码?还是我可以测试授权的更好方法?