2016-12-30 42 views
1

我写一个命令行界面一个Ruby宝石和我有这样的方法exit_error,其充当出口错误指向在处理执行的所有验证。编写Rspec的测试为一个错误条件完成与出口

def self.exit_error(code,possibilities=[]) 
    puts @errormsgs[code].colorize(:light_red) 
    if not possibilities.empty? then 
    puts "It should be:" 
    possibilities.each{ |p| puts " #{p}".colorize(:light_green) } 
    end 
    exit code 
end 

其中@errormsgs是散列的键是错误代码和它们的值是对应的错误消息。

这样,我可能会给用户自定义错误信息写入验证,如:

exit_error(101,@commands) if not valid_command? command 

其中:

@errormsgs[101] => "Invalid command." 
@commands = [ :create, :remove, :list ] 

和用户输入一个错误的命令,会收到这样的错误信息:

Invalid command. 
It should be: 
    create 
    remove 
    list 

与此同时,这样我可能的bash脚本检测完全错误代码谁造成退出条件,这对我的宝石非常重要。

一切正常用这种方法和这种策略为一体。但我必须承认,我没有先写测试就写了所有这些。我知道,我知道...对我感到羞耻!

现在,我与宝石做的,我想提高我的代码覆盖率。其他一切都是由本书完成的,首先编写测试代码,然后再测试代码。所以,对这些错误情况进行测试也是非常好的。

它发生,我真的不知道该怎么写Rspec的测试,以这种特殊情况下,当我使用exit中断处理。有什么建议么?

更新 =>这宝石是一个“编程环境”完全的bash脚本的一部分。其中一些脚本需要准确地知道中断命令的执行情况的错误情况。

+0

什么是你想要与此正好'bash'办? – Inian

+0

@Inian这个gem是有很多bash脚本的“编程环境”的一部分。其中一些脚本需要知道此Ruby命令行界面返回的错误代码,以便它们可以相应地执行操作。 –

+0

您可以通过执行'$?'来获取任何命令的返回码,您可以直接检查其值是否成功/失败检查。 – Inian

回答

2

例如:

class MyClass 
    def self.exit_error(code,possibilities=[]) 
    puts @errormsgs[code].colorize(:light_red) 
    if not possibilities.empty? then 
     puts "It should be:" 
     possibilities.each{ |p| puts " #{p}".colorize(:light_green) } 
    end 
    exit code 
    end 
end 

你可以写它的RSpec的是这样的:

describe 'exit_error' do 
    let(:errormsgs) { {101: "Invalid command."} } 
    let(:commands) { [ :create, :remove, :list ] } 
    context 'exit with success' 
    before(:each) do 
     MyClass.errormsgs = errormsgs # example/assuming that you can @errormsgs of the object/class 
     allow(MyClass).to receive(:exit).with(:some_code).and_return(true) 
    end 

    it 'should print commands of failures' 
     expect(MyClass).to receive(:puts).with(errormsgs[101]) 
     expect(MyClass).to receive(:puts).with("It should be:") 
     expect(MyClass).to receive(:puts).with(" create") 
     expect(MyClass).to receive(:puts).with(" remove") 
     expect(MyClass).to receive(:puts).with(" list") 
     MyClass.exit_error(101, commands) 
    end 
    end 

    context 'exit with failure' 
    before(:each) do 
     MyClass.errormsgs = {} # example/assuming that you can @errormsgs of the object/class 
     allow(MyClass).to receive(:exit).with(:some_code).and_return(false) 
    end 

    # follow the same approach as above for a failure 
    end 
end 

当然,这是你的规格首要前提,如果你复制可能不只是工作并粘贴代码。你将不得不做一些阅读和重构,以获得rspec的绿色信号。

+0

谢谢!是的,我知道我必须适应,但是你把我放在正确的轨道上。我不知道如何开始它。 –