ruby - Best approach to testing methods run from initialize with rspec -


i have following code (chess implementation, i'm going through theodinproject.com path):

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 

i need test ask_for_move_details("from"/"to") methods run when object instance being created.

the goal e.g. make @from variable value of "a1" , @to variable "a6" value. far have came this:

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

but doesn't work, @from gets nil value , test fails.

i know initialize method should not tested @ all, situation makes impossible create instance of object , therefore test methods. should refactor code?

ask_for_move_details("from"/"to") can stubbed using allow_any_instance_of with.

for example:

class   def a(b)   end end  describe   before     allow_any_instance_of(a).to receive(:a).with(1) { 2 }     allow_any_instance_of(a).to receive(:a).with(2) { 3 }   end        expect(a.new.a(1)).to eq 2     expect(a.new.a(2)).to eq 3   end end 

so, value returned ask_for_move_details can stubbed depending on argument passed method:

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" } 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -