【问题标题】:How to write an rspec for raise, rescue block如何为 raise、rescue 块编写 rspec
【发布时间】:2021-07-05 08:20:07
【问题描述】:

我想写rspec来测试这个方法

def path_exception
  begin
    # @path value need to mocked/stubbed if needed.
    raise if Dir[File.join(@path, '**/*.rb')].empty?
  rescue 
    puts 'Not appropriate path found'
  end
end

我已经编写了这个 rspec 并且只调用了该方法,但它仍然没有任何期望地成功

context '#wrong_path_exception' do
  it 'raises exception when path is not valid' do
    operation.path_exception
  end
end 

如果条件为真/假和救援,编写 rspec 的正确方法是什么。

【问题讨论】:

  • 如果我正确理解了代码,该方法不会引发异常——它会自行拯救引发的异常并打印一条消息。在这种情况下,您可以使用 RSpec 的output matcher
  • 顺便说一句,您不应该对控制流使用异常。只需使用您的if 表达式而不使用raiserescue
  • 如果我只调用 rspec operation.path_exception 中的方法,它会成功。没想到为什么会成功?
  • “没想到它会成功,为什么?”——这就是 RSpec 的工作方式。没有期望的例子目前不会失败。有关见解,请参阅 GitHub 问题 #759 和(现已关闭)#404
  • allow($stdout).to receive(:write) #avoid puts on console operation.wrong_path_exception expect {puts}.to output.to_stdout #期待一个put块

标签: ruby rspec


【解决方案1】:

虽然您的方法调用了raise,但由于rescue,该异常对外部不可见,这会将其转换为输出到标准输出。

您可以通过output matcher 设置期望值,例如:

expect { operation.path_exception }.to output('Not appropriate path found').to_stdout

请注意,您不需要异常来生成输出。您可以像 if 表达式一样使用 control expressions

def path_exception
  if Dir[File.join(@path, '**/*.rb')].empty?
    puts 'Not appropriate path found'
  end
end

但是根据方法的名称 (path_<b>exception</b>) 我认为您实际上想引发异常。所以实际的解决方法可能是删除rescue:

def path_exception
  if Dir[File.join(@path, '**/*.rb')].empty?
    raise 'Not appropriate path found'
  end
end

连同raise_error matcher:

expect { operation.path_exception }.to raise_error('Not appropriate path found')

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2017-08-23
    • 2019-11-07
    • 2013-07-13
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多