2017-08-14 44 views
0

我有以下代碼(國際象棋的實現,我經歷theodinproject.com路徑):最好的測試方法的方法從初始化運行使用RSpec

class Move 
def initialize(player, board) 
    @player  = player 
    @board  = board 
    @from  = ask_for_move_details("from") 
    @from_sq = @board[@from.to_sym] 
    @from_piece = @from_sq[:piece] 
    @to   = ask_for_move_details("to") 
    @to_sq  = @board[@to.to_sym] 
    make_a_move if move_allowed? 
end 

def ask_for_move_details(from_or_to) 
    begin 
    msg_ask_for_move_details(@player, from_or_to) 
    chosen_address = gets.chomp.to_s 
    raise unless address_valid?(chosen_address) 
    rescue 
    msg_move_not_allowed 
    retry 
    end 
    chosen_address 
end 
... 
end 

我需要測試其運行時ask_for_move_details("from"/"to")方法對象實例正在創建中。

目標是例如使@from變量得到值"a1"@to變量得到"a6"值。到目前爲止,我想出了只有這個:

allow(Move).to receive(:gets).and_return("a1", "a6") 

,但它不工作,因爲@from得到零值,測試失敗。

我知道初始化方法根本不應該被測試,但是這種情況使得不可能創建對象的實例並因此測試它的方法。我應該重構代碼嗎?

回答

0

ask_for_move_details("from"/"to")可以使用allow_any_instance_ofwith殘留。

例如:

class A 
    def a(b) 
    end 
end 

describe do 
    before do 
    allow_any_instance_of(A).to receive(:a).with(1) { 2 } 
    allow_any_instance_of(A).to receive(:a).with(2) { 3 } 
    end 

    it do 
    expect(A.new.a(1)).to eq 2 
    expect(A.new.a(2)).to eq 3 
    end 
end 

所以,通過ask_for_move_details返回值可以根據傳遞給此方法的參數存根:

allow_any_instance_of(Move).to receive(:ask_for_move_details).with("from") { "a1" } 
allow_any_instance_of(Move).to receive(:ask_for_move_details).with("to") { "a6" } 
+0

這工作!非常感謝 :) – sloneorzeszki