2011-08-09 3 views
5

rspecを使用して、私のApplicationControllerにあるフィルタをテストしようとしています。私が持っているspec/controllers/application_controller_spec.rbApplicationControllerフィルタ、Railsをテストする

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 

を私の意図は、フラッシュを設定しますAjaxの動作を模擬して、フラッシュがクリアされたことを次の要求に確認するテストのためでした。

私は、ルーティングエラーを取得しています:

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

はしかし、私はこれをテストしようとしている方法と間違って複数のものと予想しています。どのように私は、アプリケーション全体のフィルタをテストするためにApplicationControllerのモックメソッドを作成することができます

after_filter :no_xhr_flashes 

    def no_xhr_flashes 
    flash.discard if request.xhr? 
    end 

:?フィルタは次のように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 
関連する問題