2014-05-23 44 views
0

我需要編寫測試傳遞給方法的參數的示例。我該如何幹預使用預期參數調用方法的斷言?

選項1是返回接收到的參數作爲拍攝對象,驗證部分可以很簡潔:

subject do 
    color = nil 
    pen_double.should_receive(:color=) do |arg| 
    color = arg 
    end 
    color 
end 

context ... 
    it { should == 'red' } 
end 

context ... 
    it { should == 'green' } 
end 

此選項的問題是,「主題」部分是笨重。當我開始測試其他方法時(這裏有很多方法需要測試),它就成了一個大問題。

選項#2不使用「主題」。取而代之的是:

context ... 
    it { pen_double.should_receive(:color=).with('red') } 
end 

context ... 
    it { pen_double.should_receive(:color=).with('green') } 
end 

很明顯,'it'部分不夠乾燥。

有沒有辦法,我忽略了第三個選項?

回答

0

它不是一個真正的不同選擇,但你可以通過提取一個輔助方法改善選項2:

context ... 
    it { should_be_set_to 'red' } 
end 

context ... 
    it { should_be_set_to 'green' } 
end 

def should_be_set_to(color) 
    pen_double.should_receive(:color=).with color 
end 

即幹,比用對象塊做起來更簡潔,可以理解爲一個沒有閱讀輔助方法的學位。 (你可能會想出比我更好的方法名稱,因爲你知道該域名。)

相關問題