如何指定退出或中止的方法
我有一个从 CLI 触发的方法,该方法具有一些显式退出或中止的逻辑路径。我发现,在为此方法编写规范时,RSpec 将其标记为失败,因为退出是异常。这是一个简单的示例:
def cli_method
if condition
puts "Everything's okay!"
else
puts "GTFO!"
exit
end
end
我可以使用 should raise_error(SystemExit)
将规范包装在 lambda 中,但这会忽略块内发生的任何断言。需要明确的是:我不是在测试退出本身,而是在测试退出之前发生的逻辑。我该如何规范这种类型的方法?
I have a method being triggered from a CLI that has some logical paths which explicitly exit or abort. I have found that when writing specs for this method, RSpec marks it as failing because the exits are exceptions. Here's a a bare bones example:
def cli_method
if condition
puts "Everything's okay!"
else
puts "GTFO!"
exit
end
end
I can wrap the spec in a lambda with should raise_error(SystemExit)
, but that disregards any assertions that happen inside the block. To be clear: I'm not testing the exit itself, but the logic that happens before it. How might I go about speccing this type of method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
涵盖 Rspec 3 的预期语法的新答案。
测试输出
只是为了测试您实际想要的内容(即您没有测试异常或值响应)输出到 STDOUT 的内容。
当
condition
为 false当
condition
为 true 时请注意,
output("String").to_...
可以接受Regex< /代码> 例如。
它还可以从
stderr
捕获,例如。(对于 OP 的示例,这将是一个更好的发送位置。)
测试退出
您可以单独测试错误条件是否也会引发
SystemExit
New answer to cover Rspec 3's expect syntax.
Testing the output
Just to test what you actually want (ie. you're not testing the exception, or a value response,) what has been output to STDOUT.
When
condition
is falseWhen
condition
is trueNote that
output("String").to_...
can accept aRegex
eg.It can also capture from
stderr
eg.(Which would be a better place to send it, for the OP's example.)
Testing the Exit
You can separately test that the false condition also raises
SystemExit
只需将您的断言放在 lambda 之外,例如:
当我运行 rspec 时,它正确地告诉我:
是否有任何情况这对您不起作用?
编辑:我在 lambda 内部添加了一个“退出”调用,以处理
logic_and_exit
不退出的情况。编辑2:更好的是,只需在测试中执行以下操作:
Simply put your assertions outside of the lambda, for example:
When I run rspec, it correctly tells me:
Is there any case where this wouldn't work for you?
EDIT: I added an 'exit' call inside the lambda to hande the case where
logic_and_exit
doesn't exit.EDIT2: Even better, just do this in your test:
我没有看到将测试放在 lambda 内部或外部有什么区别。无论哪种情况,失败消息都有点神秘:
I don't see a difference putting tests inside or outside the lambda. In either case, the failure message is a bit cryptic: