Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
How do you use flexmock or mocha to test user interaction?
Feng Tien
11/12/2007 5:05:00 AM
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!
--
Posted via
http://www.ruby-...
.
1 Answer
Giles Bowkett
11/12/2007 2:54:00 PM
0
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.bl...
Portfolio:
http://www.gilesg...
Tumblelog:
http://giles.t...
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
How do you use flexmock or mocha to test user interaction?
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password