【问题标题】:why can't I raise Mongoid::Errors::DocumentNotFound in RSpec functional testing?为什么我不能在 RSpec 功能测试中提出 Mongoid::Errors::DocumentNotFound ?
【发布时间】:2012-04-18 01:57:25
【问题描述】:

我正在使用 rspec-rails (2.8.1) 对使用 mongoid (3.4.7) 的 rails 3.1 应用程序进行功能测试以实现持久性。我正在尝试在我的 ApplicationController 中为 Mongoid::Errors::DocumentNotFound 错误测试rescue_from,就像匿名控制器的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 错误?

【问题讨论】:

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


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      相关资源
      最近更新 更多