测试 ApplicationController 过滤器、Rails
我正在尝试使用 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
How can I create mockmethod on ApplicationController
to test an applicationwide filter?
I'm trying to use rspec to test a filter that I have in my ApplicationController.
In spec/controllers/application_controller_spec.rb
I have:
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
My intent was for the test to mock an ajax action that sets the flash, and then verify on the next request that the flash was cleared.
I'm getting a routing error:
Failure/Error: xhr :get, :ajaxaction
ActionController::RoutingError:
No route matches {:controller=>"application", :action=>"ajaxaction"}
However, I expect that there a multiple things wrong with how I'm trying to test this.
For reference the filter is called in ApplicationController
as:
after_filter :no_xhr_flashes
def no_xhr_flashes
flash.discard if request.xhr?
end
How can I create mock methods on ApplicationController
to test an application wide filter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使用 RSpec 测试应用程序控制器,您需要使用 RSpec 匿名控制器 方法。
您基本上在
application_controller_spec.rb
文件中设置了一个控制器操作,然后测试可以使用该操作。对于上面的示例,它可能看起来像这样。
To test an application controller using RSpec you need to use the RSpec anonymous controller approach.
You basically set up a controller action in the
application_controller_spec.rb
file which the tests can then use.For your example above it might look something like.