【发布时间】: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 的
outputmatcher。 -
顺便说一句,您不应该对控制流使用异常。只需使用您的
if表达式而不使用raise和rescue。 -
如果我只调用 rspec operation.path_exception 中的方法,它会成功。没想到为什么会成功?
-
allow($stdout).to receive(:write) #avoid puts on console operation.wrong_path_exception expect {puts}.to output.to_stdout#期待一个put块