How do you use flexmock or mocha to test user interaction?

F

Feng Tien

I can't seem to figure this out

Here's my code that takes user input



def input_money (machine)
print 'How much money would you like to put in?'
money_used = gets.chomp.to_f
#the check is not working
if money_used > @money
puts 'You do not have that much'
else
@money = @money - money_used
machine.money_used = money_used
puts 'You insert ' + money_used.to_s
end
end

My test:

def test_money_back #this checks to see if you get the right amount of
money
poo = Vending_Machine.new
bob = Person.new
bob.input_money(poo)
flexmock($stdin){|mock| mock.should_receive("gets").and_return("2")}
# I know this is wrong!
expected = poo.money_used #one of the instance variables

assert_equal 2, expected
end

Right now, since the regular unit test doesn't take any inputs, the
money_used is always going to be 0. How do I make a mock that sets the
value of money_used to 2?

I found in a different thread to use this:
flexmock($stdin){|mock| mock.should_receive("gets").and_return("junk")}

but how do you tell it which method the gets is suppose to be set as 2?
Is there some way to replace the real gets with the mock gets?

Been reading the forum and searching on google the last 2 hours, can't
figure out how this works!

thanks!
 
G

Giles Bowkett

I'm going to give you the answer, but I'm not giving it to you in
code. it's too obvious. you need to think about how flexmock works. it
attaches methods to objects and guarantees their return value. the
code you copy-pasted, you should read it and figure out what it means.
it's attaching a method to $stdin and guaranteeing the method will
return the string "junk". so attach a method to $stdin which returns 2
instead, and then call that method on $stdin.

by the way, you used the variable name "poo" - in English that's a
word that children use for feces. I definitely recommend a different
variable name. either "foo" or "shit." or, if it's a transliteration
of an Asian name, use "pu" instead. nobody wants to be called poo.

--
Giles Bowkett

Blog: http://gilesbowkett.blogspot.com
Portfolio: http://www.gilesgoatboy.org
Tumblelog: http://giles.tumblr.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top