freerange / mocha

A mocking and stubbing library for Ruby

Home Page:https://mocha.jamesmead.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mocha and Rails 7.0+ and controller tests

zenspider opened this issue · comments

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.

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".

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.

@zenspider Is this still causing a problem for you?