2012-04-18 69 views
5

我使用rspec-rails(2.8.1)來爲使用mongoid(3.4.7)進行持久性功能測試rails 3.1應用程序。我正在嘗試在我的ApplicationController中針對Mongoid :: Errors :: DocumentNotFound錯誤進行rescue_from測試,其方式與匿名控制器的rspec-rails documentation暗示可以完成的方式相同。但是,當我運行下面的測試...爲什麼我不能在RSpec功能測試中引發Mongoid :: Errors :: DocumentNotFound?

require "spec_helper" 

class ApplicationController < ActionController::Base 

    rescue_from Mongoid::Errors::DocumentNotFound, :with => :access_denied 

private 

    def access_denied 
    redirect_to "/401.html" 
    end 
end 

describe ApplicationController do 
    controller do 
    def index 
     raise Mongoid::Errors::DocumentNotFound 
    end 
    end 

    describe "handling AccessDenied exceptions" do 
    it "redirects to the /401.html page" do 
     get :index 
     response.should redirect_to("/401.html") 
    end 
    end 
end 

我得到以下意外的錯誤

1) ApplicationController handling AccessDenied exceptions redirects to the /401.html page 
    Failure/Error: raise Mongoid::Errors::DocumentNotFound 
    ArgumentError: 
     wrong number of arguments (0 for 2) 
    # ./spec/controllers/application_controller_spec.rb:18:in `exception' 
    # ./spec/controllers/application_controller_spec.rb:18:in `raise' 
    # ./spec/controllers/application_controller_spec.rb:18:in `index' 
    # ./spec/controllers/application_controller_spec.rb:24:in `block (3 levels) in <top (required)>' 

爲什麼?我怎樣才能提高這個mongoid錯誤?

回答

10

Mongoid的documentation for the exception顯示它必須被初始化。修正的工作代碼如下:

require "spec_helper" 

class SomeBogusClass; end 

class ApplicationController < ActionController::Base 

    rescue_from Mongoid::Errors::DocumentNotFound, :with => :access_denied 

private 

    def access_denied 
    redirect_to "/401.html" 
    end 
end 

describe ApplicationController do 
    controller do 
    def index 
     raise Mongoid::Errors::DocumentNotFound.new SomeBogusClass, {} 
    end 
    end 

    describe "handling AccessDenied exceptions" do 
    it "redirects to the /401.html page" do 
     get :index 
     response.should redirect_to("/401.html") 
    end 
    end 
end 
相關問題