Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if a function is called using Mocha

In my current Rails 3 app, I'm doing some unit testing to make sure that calls to update S3 are only done under certain situations. I don't want to update S3 during tests, so I'm using Mocha to stub out the behaviour. Is there a way to make sure a function is called using mocha? I've taken a look at Expectations, and unless I'm doing it wrong, it seems I have to do:

object.expects(:function_name).once

However, this does not yield the desired results: This will flag an error if function_name is called twice(which is desired), it will NOT flag an error if it is only called once(as it should), but the problem is it WILL NOT flag an error if the function is called zero times. I need a way to make sure it is called. It seems like mocha should support this, so maybe I'm doing it wrong. Any help would be greatly appreciated.

***** CORRECTION:

Turns out that I was doing it right, except that the mocha_verify method wasn't being called automatically. For anyone who is having a similar problem, check out Ole Morten Amundsen's answer over here: Mocha Mock Carries To Another Test

like image 220
pushmatrix Avatar asked Dec 09 '10 06:12

pushmatrix


1 Answers

or just

object.expects(:function_name).twice

alternatively, if it has differnet input you should test that

resultmock = mock 
object.expects(:function_name).with(someobject).returns(mock)
resultmock.expects(:something).returns(true)
object.expects(:function_name).with(resultmock)

don't know if this helps, but it should give you a kick start. FYI: 'once' is default. Good luck, do TDD (=test-first) or mocking will be a pain :)

Be sure to load mocha last, so it is really being loaded, as in my answer here: Mocha Mock Carries To Another Test

like image 51
oma Avatar answered Oct 04 '22 19:10

oma