如何指定退出或中止的方法 [英] How to spec methods that exit or abort
问题描述
我有一个从 CLI 触发的方法,该方法具有一些显式退出或中止的逻辑路径.我发现在为此方法编写规范时,RSpec 将其标记为失败,因为出口是例外.这是一个简单的例子:
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
我可以使用 should raise_error(SystemExit)
将规范包装在 lambda 中,但这会忽略块内发生的任何断言.需要明确的是:我不是在测试出口本身,而是在它之前发生的逻辑.我该如何去指定这种类型的方法?
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?
推荐答案
只需将断言放在 lambda 之外,例如:
Simply put your assertions outside of the lambda, for example:
class Foo
attr_accessor :result
def logic_and_exit
@result = :bad_logic
exit
end
end
describe 'Foo#logic_and_exit' do
before(:each) do
@foo = Foo.new
end
it "should set @foo" do
lambda { @foo.logic_and_exit; exit }.should raise_error SystemExit
@foo.result.should == :logics
end
end
当我运行 rspec 时,它正确地告诉我:
When I run rspec, it correctly tells me:
expected: :logics
got: :bad_logic (using ==)
在任何情况下这对您都不起作用吗?
Is there any case where this wouldn't work for you?
我在 lambda 中添加了一个退出"调用来处理 logic_and_exit
不退出的情况.
I added an 'exit' call inside the lambda to hande the case where logic_and_exit
doesn't exit.
更好的是,只需在测试中执行此操作:
Even better, just do this in your test:
begin
@foo.logic_and_exit
rescue SystemExit
end
@foo.result.should == :logics
这篇关于如何指定退出或中止的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!