为什么我不能在RSpec功能测试中提出Mongoid :: Errors :: DocumentNotFound?

时间:2012-04-18 01:57:25

标签: ruby-on-rails ruby-on-rails-3.1 mongoid rspec-rails

我正在使用rspec-rails(2.8.1)使用mongoid(3.4.7)对rails 3.1 app进行功能测试以实现持久性。我正在尝试在我的ApplicationController中测试rescue_from for Mongoid :: Errors :: DocumentNotFound错误,就像匿名控制器的rspec-rails documentation建议可以完成的那样。但是当我进行以下测试时...

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

1 个答案:

答案 0 :(得分: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