2012-04-18 20 views
5

Tôi đang sử dụng rspec-ray (2.8.1) để thử nghiệm chức năng ứng dụng đường ray 3.1 sử dụng mongoid (3.4.7) cho sự bền bỉ. Tôi đang cố gắng thử rescue_from cho Mongoid :: lỗi :: DocumentNotFound lỗi trong ApplicationController của tôi trong cùng một cách mà các rspec-rails documentation cho bộ điều khiển vô danh cho thấy nó có thể được thực hiện. Nhưng khi tôi chạy thử nghiệm sau đây ...Tại sao tôi không thể nâng cao Mongoid :: Lỗi :: DocumentNotFound trong thử nghiệm chức năng RSpec?

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 

tôi nhận được lỗi không mong muốn sau

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)>' 

Tại sao? Làm thế nào tôi có thể nâng lỗi mongoid này?

Trả lời

10

Mongoid's documentation for the exception cho biết nó phải được khởi tạo. Mã được sửa chữa, hoạt động như sau:

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