Soo*_*uNe 5 unit-testing rspec ruby-on-rails ruby-on-rails-3
我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)
我的目的是测试模拟设置闪存的ajax动作,然后在下一个请求中验证闪存已被清除.
我收到路由错误:
Failure/Error: xhr :get, :ajaxaction
ActionController::RoutingError:
No route matches {:controller=>"application", :action=>"ajaxaction"}
Run Code Online (Sandbox Code Playgroud)
但是,我希望我试图测试这个有多少错误.
作为参考,过滤器被调用ApplicationController为:
after_filter :no_xhr_flashes
def no_xhr_flashes
flash.discard if request.xhr?
end
Run Code Online (Sandbox Code Playgroud)
如何创建模拟方法ApplicationController来测试应用程序范围的过滤器?
要使用RSpec测试应用程序控制器,您需要使用RSpec匿名控制器方法.
您基本上在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
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2449 次 |
| 最近记录: |