freerange / mocha

A mocking and stubbing library for Ruby
https://mocha.jamesmead.org
Other
1.23k stars 158 forks source link

Stubbed methods not cleaned up post spec completion #637

Closed Bennet-Sunder closed 9 months ago

Bennet-Sunder commented 10 months ago

The original implementation of the method is replaced during the test and then restored at the end of the test. The temporary replacement method has the same visibility as the original method.

From the documentation of stubs I can see that the stubbed value gets cleared post-completion of the spec. i.e. the stubbed value doesn't get leaked between specs.

However, I noticed that in our rspec test suite, the stubbed values is persisted beyond the stubbed spec and leaks state.

Example:

it 'test 1' do
  Account.any_instance.stubs(:method_name?).returns(:method_value)
  ...
end

it 'test 2' do
  Account.current.method_name? # returns :method_value
  ...
end

One thing I noticed is that the mock_with is set as rspec in our test suite since we use rspec-mocks. config.mock_with :rspec

Could this be the reason why the stubbed value doesn't get cleared once the spec is completed, as mentioned in the docs?

floehopper commented 9 months ago

One thing I noticed is that the mock_with is set as rspec in our test suite since we use rspec-mocks. config.mock_with :rspec

Could this be the reason why the stubbed value doesn't get cleared once the spec is completed, as mentioned in the docs?

Yes, that's likely to be a problem, because from what I remember of the RSpec integration it's that configuration that triggers calls to the methods in Mocha::Hooks . If you really want to use both Mocha and RSpec mocks, then you'll have to add setup & teardown methods to the relevant tests to call the methods in Mocha::Hooks as their documentation describes.

I'm going to close this issue, because I'm confident that this should solve the problem. Feel free to re-open if not.