2011-10-06 2 views
9

저는 CanCan을 사용하여 자원을 승인하는 레일 프로젝트에 참여하고 있습니다. 사용자가 로그인하지 않았고 ajax 양식 제출을 통해 "대화"를 제출하려고하면 CanCan이 {"status":"error","message":"You must be logged in to do that!"}과 함께 401을 올바르게 올립니다 (방화 광구를 사용하여 브라우저에서이를 확인했습니다).RSpec을 사용하여 CanCan 실패 인증에 대한 응답 코드를 테스트하려면 어떻게해야합니까?

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 :하지만, 내 테스트에서 401보다는 302 응답 코드를 얻을 [: 이야기] 할당되지 않은 첫 번째 예는 여기에 포함 된

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 

성공 (양수인입니다), 두 번째는 아닙니다 :

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)>' 

나는 무슨 일이 일어나고 있는지 잘 모르겠습니다. 브라우저에 반환 된 실제 응답 코드를 테스트 할 수있는 방법이 있습니까? 아니면 인증을 테스트 할 수있는 더 좋은 방법입니까?

+0

'post : create, : format => : json'을 읽고 스펙이 도움이되는지보기 위해 스펙을 변경해보십시오. – zetetic

+0

제안 해 주셔서 감사합니다. 불행히도, 나는 여전히 : format => : json을 추가 한 후에 같은 302 코드를 얻는다. –

+1

테스트 로그를 보았습니까? – zetetic

답변

8

내 프로젝트에서 CanCan의 인증 예외를 다음 기능으로 해결했습니다. 요청이 ajax 일 때 (그리고 다른 방향으로 리디렉션되는) 401 기능 만 수행하기 때문에 브라우저에서 401을 얻었지만 내 테스트는 얻지 못했습니다. 이 요청의 차이를 계시 나는 내 테스트 로그를 확인 제안에 대한 zetetic

# 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 

감사합니다.

관련 문제