2011-08-09 43 views
5

我想使用rspec來測試我的ApplicationController中的過濾器。測試ApplicationController過濾器,導軌

spec/controllers/application_controller_spec.rb我:

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"} 

不過,我希望有一個多件事情錯了,我怎麼想測試這一點。

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