7

我正在使用 rspec-rails (2.8.1) 对使用 mongoid (3.4.7) 的 rails 3.1 应用程序进行功能测试以实现持久性。我正在尝试在我的 ApplicationController 中为 Mongoid::Errors::DocumentNotFound 错误测试rescue_from,就像匿名控制器的rspec-rails 文档表明它可以完成一样。但是当我运行以下测试时......

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 错误?

4

1 回答 1

10

Mongoid 的异常文档显示它必须被初始化。更正后的工作代码如下:

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
于 2012-04-18T11:23:48.707 回答