ruby-on-rails - 测试 ApplicationController 过滤器、Rails

标签 ruby-on-rails ruby-on-rails-3 unit-testing rspec

我正在尝试使用 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

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

我收到路由错误:
 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 测试应用程序 Controller ,您需要使用 RSpec anonymous controller方法。

您基本上在 application_controller_spec.rb 中设置了 Controller 操作。然后测试可以使用的文件。

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

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

关于ruby-on-rails - 测试 ApplicationController 过滤器、Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6990661/

相关文章:

python - Flask 蓝图单元测试

ruby-on-rails - Rails link_to params .id 而不是/id

ruby-on-rails - 将 PG::Result 转换为 Active Record 模型

ruby-on-rails - Rails 3 中的 Ajax 错误处理

ruby-on-rails - 运行 rake 任务时如何跳过 Rails 初始值设定项的加载?

ruby-on-rails - 如何仅在登录时运行 setInterval ajax 调用?

ruby-on-rails - Heroku:Rails 服务器永远工作

java - 使用 Java 8 时钟对类进行单元测试

reactjs - 我什么时候应该使用快照测试?

ruby-on-rails - 如何在 Rails 中实现这种渐进式参与/延迟注册?