2011-08-09 20 views
5

ApplicationController'ımda bulunan bir filtreyi test etmek için rspec kullanmaya çalışıyorum.Test UygulamasıKontrol Cihazı Filtreleri, Rayları

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 

Benim niyet flaş ayarlayan bir ajax eylemi alay etmek test için, ve sonra flaş temizlendiğini belirten sonraki istek üzerine doğrulamak: spec/controllers/application_controller_spec.rb yılında

ben var.

Ben bir yönlendirme hatayı alıyorum:

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

Ancak, ben beklemek ben bu sınamak çalışıyorum nasıl yanlış orada birden şeyler.

after_filter :no_xhr_flashes 

    def no_xhr_flashes 
    flash.discard if request.xhr? 
    end 

nasıl bir uygulama geniş bir filtre test etmek ApplicationController üzerinde sahte yöntemleri oluşturabilirsiniz:

Başvuru için filtre olarak ApplicationController yılında denir?

cevap

8

RSpec kullanarak bir uygulama denetleyicisini test etmek için RSpec anonymous controller yaklaşımını kullanmanız gerekir.

Temel olarak, denetimlerin kullanabileceği application_controller_spec.rb dosyasında bir denetleyici eylemi oluşturdunuz.

Yukarıdaki örneğinizde bunun gibi bir şey görünebilir.

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