freerange / mocha

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

Mocha and Rails 7.0+ and controller tests #639

Open zenspider opened 9 months ago

zenspider commented 9 months ago

I'm in the midst of an upgrade and getting bit by mocha a fair amount and don't see any related issues. Namely this:

https://github.com/rails/rails/blob/main/actionpack/lib/action_controller/test_case.rb#L504

Is clearing out the @mocha ivar stored on the test controller on EVERY request such that any test with 2+ requests will have mocha fail any expectations on the second request because the mockery (?) gets wiped out.

A possible workaround is to pop this into the topmost setup/before:

    # forces R7 controller ivar cleaning to keep expectations across requests
    @controller.instance_variable_set(:@mocha, nil)

but I'm having to do that in a lot of controller tests and I figure I'm doing something terribly wrong.

How am I the only one reporting this? Are we doing something weird? Are we the only ones left still using controller tests? Integration tests are a HUGE leap for us and I imagine a lot of legacy rails apps.

zenspider commented 9 months ago

Example of this going bad:

#>>> puts exception
unexpected invocation: #<Api::V2::TicketFieldsController:0x3c528>.statsd_client()
unsatisfied expectations:
- expected exactly once, invoked never: #<Api::V2::TicketFieldsController:0x3c528>.statsd_client(any_parameters)
...

the stubbed method on the controller in still the mocha bypass, but with the mockery nilled out the call is "unexpected".

floehopper commented 8 months ago

I'm dealing with a family bereavement at the moment, so I don't have much time to investigate this.

I've been using controller tests in a Rails 7 project recently and haven't come across this issue, although to be fair I can't be sure we did any stubbing of controller methods.

Making multiple requests in a single controller test method seems somewhat unusual to me - perhaps that's what makes your use case different - or have I misunderstood?

If you can share a minimal example of code that reproduces the problem, I'll try to find some time to investigate.

floehopper commented 8 months ago

@zenspider Is this still causing a problem for you?