Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unstub Mocha mock?

I have the following mocha mock that works great.

In a test.rb file:

setup do
  Date.stubs(:today).returns(Date.new(2011, 7, 19)) 
  Time.stubs(:now).returns(Time.new(2011,1,1,9,0))
end

The problem is that the timing is broken for the tests. After the tests run the date and time objects are still mocked.(!)

Finished in -21949774.01594216 seconds.

I added the following:

teardown do
  Date.unstubs(:today)
  Time.unstubs(:now)
end

This throws the following error for each test: WARNING: there is already a transaction in progress

Is this the proper way to unstub? Is it better to unstub at the end of the test file or even at the end of unit test suite?

Working in Rails 3.07 and Mocha 0.9.12

Thanks.

like image 641
B Seven Avatar asked Sep 12 '11 18:09

B Seven


2 Answers

I don't know if this is fully your problem, but it is just unstub, not pluralized.

Other than that, there should be no issue. You definitely want to unstub after each test (or set of tests, if a bunch of tests need the stubbing) because once stubbed, it will stay stubbed, and that can screw up other tests.

like image 93
MrDanA Avatar answered Sep 27 '22 23:09

MrDanA


The accepted answer is spreading misinformation and should be considered harmful.

One of the main purposes of a mocking library like Mocha is to provide automatic mock/stub teardown as part of the integration to various testing libraries. In fact if you look at the GitHub repo for Mocha you will see that significant maintenance effort is put into making Mocha work smoothly with all the versions of several different testing frameworks.

If this isn't working properly then you need to figure out why Mocha's built-in teardown isn't working. Unstubbing manually in your own teardown is just papering over the problem, and could hide subtler issues with stub leakage or Mocha otherwise misbehaving.

If I had to take a wild guess money would be on your stub somehow being run outside of an actual test because that's the most common cause I've seen for this kind of thing in the wild, but there's not enough information from the question to really ascertain.

like image 39
gtd Avatar answered Sep 27 '22 23:09

gtd