2011-08-09 2 views
5

rspec을 사용하여 ApplicationController에있는 필터를 테스트하려고합니다.ApplicationController 필터, 레일

require 'spec_helper' 
describe ApplicationController do 
    it 'removes the flash after xhr requests' do  
     controller.stub!(:ajaxaction).and_return(flash[:notice]='FLASHNOTICE') 
     controller.stub!(:regularaction).and_return() 
     xhr :get, :ajaxaction 
     flash[:notice].should == 'FLASHNOTICE' 
     get :regularaction 
     flash[:notice].should be_nil 
    end 
end 

내 의도는 플래시를 설정하는 아약스 조치를 조롱하기 위해 테스트 한 후 플래시가 지워 졌음을 다음 요청에 확인 : spec/controllers/application_controller_spec.rb에서

나는 있습니다.

내가 라우팅 오류를 받고 있어요 :

Failure/Error: xhr :get, :ajaxaction 
ActionController::RoutingError: 
    No route matches {:controller=>"application", :action=>"ajaxaction"} 

그러나, 내가 기대하는 내가 이것을 테스트하기 위해 노력하고있어 방법에있어 문제점이 여러 가지.

after_filter :no_xhr_flashes 

    def no_xhr_flashes 
    flash.discard if request.xhr? 
    end 

이 어떻게 응용 프로그램 다양한 필터를 테스트 할 수 ApplicationController에 모의 방법을 만들 수 있습니다

는 참고 용 필터 등 ApplicationController에라고?

답변

8

RSpec을 사용하여 응용 프로그램 컨트롤러를 테스트하려면 RSpec anonymous controller 접근 방법을 사용해야합니다.

기본적으로 테스트에서 사용할 수있는 application_controller_spec.rb 파일에 컨트롤러 동작을 설정합니다.

위 예제의 경우 다음과 유사 할 수 있습니다.

require 'spec_helper' 

describe ApplicationController do 
    describe "#no_xhr_flashes" do 
    controller do 
     after_filter :no_xhr_flashes 

     def ajaxaction 
     render :nothing => true 
     end 
    end 

    it 'removes the flash after xhr requests' do  
     controller.stub!(:ajaxaction).and_return(flash[:notice]='FLASHNOTICE') 
     controller.stub!(:regularaction).and_return() 
     xhr :get, :ajaxaction 
     flash[:notice].should == 'FLASHNOTICE' 
     get :regularaction 
     flash[:notice].should be_nil 
    end 
    end 
end