首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试ApplicationController过滤器,Rails

测试ApplicationController过滤器,Rails
EN

Stack Overflow用户
提问于 2011-08-09 10:01:55
回答 1查看 2.5K关注 0票数 6

我正在尝试使用rspec来测试我的ApplicationController中的过滤器。

spec/controllers/application_controller_spec.rb中,我有:

代码语言:javascript
复制
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

我的目的是让测试模拟一个设置flash的ajax操作,然后在下一个请求时验证flash是否被清除。

我收到一个路由错误:

代码语言:javascript
复制
 Failure/Error: xhr :get, :ajaxaction
 ActionController::RoutingError:
   No route matches {:controller=>"application", :action=>"ajaxaction"}

然而,我认为我尝试测试它的方式存在多方面的错误。

为了便于参考,在ApplicationController中将过滤器调用为:

代码语言:javascript
复制
  after_filter :no_xhr_flashes

  def no_xhr_flashes
    flash.discard if request.xhr?
  end
EN

回答 1

Stack Overflow用户

发布于 2011-10-20 10:00:25

要使用RSpec测试应用程序控制器,您需要使用RSpec anonymous controller方法。

您基本上在application_controller_spec.rb文件中设置了一个控制器操作,然后测试就可以使用它了。

对于上面的示例,它可能看起来像这样。

代码语言:javascript
复制
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
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6990661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档