【问题标题】:RSpec: Testing rescue_fromRSpec:测试rescue_from
【发布时间】:2010-12-16 23:35:30
【问题描述】:

我如何测试rescue_from 是RSpec?我想确保如果引发异常之一,控制器正确设置闪光灯并进行重定向。有没有办法模拟异常?

  rescue_from PageAccessDenied do
    flash[:alert] = "You do not have the necessary roles to access this page"
    redirect_to root_url
  end

  rescue_from CanCan::AccessDenied do |exception|
    flash[:alert] = exception.message
    redirect_to root_url
  end

【问题讨论】:

    标签: testing rspec


    【解决方案1】:

    假设您有一个引发异常的authorize! 方法,您应该能够执行以下操作:

      describe "rescue_from exceptions" do
        it "rescues from PageAccessDenied" do
          controller.stub(:authorize!) { raise PageAccessDenied }
          get :index
          response.should redirect_to("/")
          flash[:alert].should == "You do not have the necessary roles to access this page"
        end
      end
    

    【讨论】:

    • 我不理解存根...在我看来,您正在让控制器在测试中引发该错误。如果您只是在测试中伪造它,您如何确定它会在生产中引发错误?
    • @hamstar 这仅测试rescue_from 块的行为。为确保authorize! 引发错误,您将为此编写另一个测试。大概这发生在图书馆(CanCan?)中,作者在那里编写了测试。
    • 使用 rspec 的新 ':expect' 语法,它看起来像这样:expect(controller).to receive(:authorize!).and_raise(PageAccessDenied)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2011-06-09
    • 2021-09-26
    • 1970-01-01
    • 2014-05-18
    • 2011-08-27
    • 2017-05-23
    相关资源
    最近更新 更多