views:

53

answers:

1

Say I have the following method:

#Create new guest object. Add it to array and save it to disc
  def new_guest
    printf "First name: "
    first_name = gets.chomp
    printf "Last name: "
    last_name = gets.chomp
    printf "Adress: "
    adress = gets.chomp
    printf "Phone:"
    phone = gets.chomp
    new_guest = Guest.new(first_name, last_name, adress, phone)
    @guests.push(new_guest)
    File.open("guests", 'w') {|f| Marshal.dump(@guests, f) }
  end

How would I write a unit test for it that can pass in values for the gets? All I found was this article but I don't know how to use it in this case. Im also wondering if there is a good way to mark things that should not run when run from a test? I might not want to save the dummy objects for example.

+4  A: 

The reason you are struggling to test this method is because the method is doing too much. This method is collecting input from the user, creating a new object, adding the record to a list and saving it to disk. You have UI, Data Access and Object persistence all wrapped up in one method.

Try splitting the method into smaller methods and then test those individually. At the very least you could have 2 methods as follows :-

def new_guest(first_name, last_name, address, phone)
  guest = Guest.new(first_name, last_name, address, phone)
  @guests.push(new_guest)
  File.open("guests", 'w') {|f| Marshal.dump(@guests, f) }
end

def get_guest_data()
   printf "First name: "
    first_name = gets.chomp
    printf "Last name: "
    last_name = gets.chomp
    printf "Adress: "
    adress = gets.chomp
    printf "Phone:"
    phone = gets.chomp
    [ first_name, last_name, address, phone]
end

Then within your unit test you can test new_guest by passing in values generated within your test cases

Steve Weet
That is very true, method was mostly a (bad) example but your answer made me think that perhaps I should be testing the input validation (which there is none in the example) instead of the actual input. If I validate it correctly the input shouldn't matter right?
Patrik Björklund
Well you should certainly be testing any input validation to ensure that it does the correct thing for standard and edge conditions. If you have a function that also collects the input then you should test that function by assuring that the data is collected and passed to the other function correctly and your linked article has good examples on how to do that.
Steve Weet