12

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

Community
  • 1
  • 1
pushmatrix
  • 726
  • 1
  • 9
  • 23
  • 2
    you should mark an answer as accepted. That way you don't waste good people's time, those that browse for "unanswered Q" to selflessly help people like you and me. – oma Dec 15 '10 at 07:27

2 Answers2

10

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

Community
  • 1
  • 1
oma
  • 38,642
  • 11
  • 71
  • 99
  • Turns out your answer over here http://stackoverflow.com/questions/3118866/mocha-mock-carries-to-another-test/4375296#4375296 solved my problem. The mocha_verify hook wasn't being called due to the ordering bundler did with the mocha gem. – pushmatrix Dec 10 '10 at 01:40
  • wow, that's a first-timer for me :) I just love Mocha and want to help others to use it. I've add my other answer to my answer here, so you may mark it as accepted. Glad I could help! – oma Dec 10 '10 at 10:09
6

Try:

object.expects(:function_name).at_least_once

Have a look at the docs: http://mocha.rubyforge.org/classes/Mocha/Expectation.html#M000042

rtacconi
  • 14,317
  • 20
  • 66
  • 84
  • I had already tried it, but it turns out my problem was the mocha_verify wasn't being called due to the load order of the mocha gem. Strange beans... – pushmatrix Dec 10 '10 at 01:41