2016-12-30 45 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

謝謝!是的,我知道我必須適應,但是你把我放在正確的軌道上。我不知道如何開始它。 –