[Uw-ruby] good question from James (how to test user interaction)

Ryan Davis ryand-uwruby at zenspider.com
Sun Nov 11 15:32:32 PST 2007


On Nov 9, 2007, at 10:43 , Clark, James (Port Hueneme) wrote:

> One main question that perhaps can be addressed next class is that  
> during writing tests for my parking garage implementation, howshould  
> user interface methods be tested when input is retrieved with  
> 'gets'? My parking garage class has two methods for getting a ticket  
> and for exiting the gate but are untested other than some code I  
> commented out at the bottom that I was running manually

Very good question so I thought I'd pull it up to the list.

First off, there isn't anything in the homework saying you have to  
interact with the user running the code. All you really have to  
interact with is the test driving the code. So where you might have  
something like:

     @parking_garage = ParkingGarage.new 10
     assert_equal "Garage open with 10 spots left",  
@parking_garage.open_garage

You could model it as:

     @parking_garage = ParkingGarage.new 10
     assert_equal 10, @parking_garage.open_garage

Second, testing input/output makes your tests more complex, but it is  
still pretty easy to do. If you do want to test user interaction,  
there are a couple ways to
do it. Mocks are one. I prefer a simpler (some would say simplistic)
approach:

> 503 % ruby -rstringio -e '$stdin = StringIO.new "hi\nexit\n"; p gets'
> "hi\n"

Just use the StringIO objects to replace the values of stdin/out  
around where you want to test. Make sure to save off and put the  
original stdin/out back afterwards or your tests will never output.

While it is up to you how you design these requirements, modeling that  
is separate from UI is more flexible to use in multiple contexts. You  
can have both a command-line interface to the garage and a web  
interface using the same modeling code. You can also have different  
views of the same data like, one program hooked up and running the  
gate and another program telling the parking lot owner how much money  
they made in the last week.



More information about the Uw-ruby mailing list