开发者

Testing ApplicationController Filters, Rails

开发者 https://www.devze.com 2023-03-26 15:20 出处:网络
I\'m trying to use rspec to test a filter that I have in my ApplicationController. In spec/contr开发者_开发百科ollers/application_controller_spec.rb I have:

I'm trying to use rspec to test a filter that I have in my ApplicationController.

In spec/contr开发者_开发百科ollers/application_controller_spec.rb I have:

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

My intent was for the test to mock an ajax action that sets the flash, and then verify on the next request that the flash was cleared.

I'm getting a routing error:

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

However, I expect that there a multiple things wrong with how I'm trying to test this.

For reference the filter is called in ApplicationController as:

  after_filter :no_xhr_flashes

  def no_xhr_flashes
    flash.discard if request.xhr?
  end

How can I create mock methods on ApplicationController to test an application wide filter?


To test an application controller using RSpec you need to use the RSpec anonymous controller approach.

You basically set up a controller action in the application_controller_spec.rb file which the tests can then use.

For your example above it might look something like.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消