我正在尝试使用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发布于 2011-10-20 10:00:25
要使用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
endhttps://stackoverflow.com/questions/6990661
复制相似问题