RSpec:测试rescue_from

时间:2010-12-16 23:35:31

标签: testing rspec

如何测试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

1 个答案:

答案 0 :(得分:15)

假设您有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