测试块救援 Errno::ENOENT

Test a block rescue Errno::ENOENT

我看到当你按一个按钮太多次时会发生错误,我用救援处理了它,所以控制器是:

 def all_list
  filename = "#{current_organization.name.gsub(' ', '_')}.zip"
  temp_file = Tempfile.new(filename)
  begin
    #things to create a zip
  rescue Errno::ENOENT
   puts 'Something went wrong'
   redirect_to all_list_report_path
  ensure
   temp_file.close
   temp_file.unlink
  end
 end

我用 rspec 尝试了很多东西来测试这个救援块,我最后一次尝试是:

  context 'with a logged user that try to' do
   before do
    login(member1.user)
    allow(ReportsController).to receive(:all_list).and_raise(Errno::ENOENT)
   end
   it 'throws the error but downloads the zip' do
    get :all_list
    expect(ReportsController).to receive(:all_list).and_raise(Errno::ENOENT)
   end
  end

它似乎有效,但没有涵盖块救援,我试图查看是否使用 puts 'Something went wrong' 调用了块,但显然没有打印任何内容。

我正在寻找一种有效覆盖该块的方法。欢迎任何帮助。

您必须为在 begin 块内调用的方法引发错误。为 all_list 方法引发错误将永远不会执行开始和救援块。

def all_list
  filename = "#{current_organization.name.gsub(' ', '_')}.zip"
  temp_file = Tempfile.new(filename)
  begin
    things_to_create_a_zip
  rescue Errno::ENOENT
   puts 'Something went wrong'
   redirect_to all_list_report_path
  ensure
   temp_file.close
   temp_file.unlink
  end
 end

允许things_to_create_a_zip方法引发错误Errno::ENOENT,将执行救援块。

context 'with a logged user that try to' do
   before do
    login(member1.user)
    allow(subject).to receive(:things_to_create_a_zip).and_raise(Errno::ENOENT)
   end
   it 'redirect to all_list_report_path' do
    get :all_list
    expect(response).to redirect_to(all_list_report_path)
   end
end