Reputation: 1237
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.
Upvotes: 0
Views: 1299
Reputation: 28422
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
Upvotes: 4