ruby-on-rails – 测试ApplicationController过滤器,Rails
发布时间:2020-12-17 03:35:03 所属栏目:百科 来源:网络整理
导读:我正在尝试使用rspec来测试我在ApplicationController中的过滤器. 在spec / controllers / application_controller_spec.rb中我有: require 'spec_helper'describe ApplicationController do it 'removes the flash after xhr requests' do controller.stub
我正在尝试使用rspec来测试我在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"} 但是,我希望我试图测试这个有多少错误. 作为参考,过滤器在ApplicationController中被调用为: after_filter :no_xhr_flashes def no_xhr_flashes flash.discard if request.xhr? end 如何在ApplicationController上创建模拟方法来测试应用程序范围的过滤器? 解决方法
要使用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |