RSpec:测试救援_from

问题描述 投票:0回答:2

如何测试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
2个回答
14
投票

假设您有一个

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

0
投票

我采用了shared_example方法:

我们希望避免存根/嘲笑

initialize
方法,如果你尝试的话,会有很多警告提醒你。相反,我们可以利用
new
exception
方法,具体取决于您的错误是如何提出的。

我注意到,由

raise
显式调用的错误需要在
exception
方法上进行检查。

示例代码:

 def validate_params
   params.require(:param_key_1)
   params.require(:param_key_2)

   raise ExpectedError if something_wrong?
 end
shared_examples_for :no_errors_raised do
  it { expect { subject }.not_to raise_error }
end

shared_examples_for :rescued_from do |error_class, invocation_method: :new|
  before do
    # complains if the expected error is not invoked
    expect(error_class).to receive(invocation_method).and_call_original
  end

  # complains if the error is not rescued
  it_behaves_like :no_errors_raised
end

it_behaves_like :rescued_from, ActionController::ParameterMissing # => when param_key_1 or param_key_2 is missing
it_behaves_like :rescued_from, ExpectedError, method: :exception # => when something_wrong? == true

我已经在本地进行了测试,当使用

rescue_from
方法时,它似乎工作正常,因此您只需调用相同的共享示例,如下所示:

it_behaves_like :rescued_from, PageAccessDenied
it_behaves_like :rescued_from, CanCan::AccessDenied
© www.soinside.com 2019 - 2024. All rights reserved.