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