Stubbing/Mocking a controller action in a System Spec

Skip to first unread message

Jack Royal-Gordon

Mar 29, 2021, 10:31:13 PMMar 29
I’m trying to test how my screen handles an error return from an Ajax call. In  order to accomplish this, I need the Ajax call to return the error response, and I’d like to do that by mocking the controller action. I’d like to do something like:

allow_any_instance_of(BooksController).to receive(:modify) { render status: :not_found, json: "Unknown book: #{}" }

But the render call gives an “undefined method” error, presumably because I’m in a test and not in a controller method. Is there a way for me to mock this behavior, or do I somehow have to manipulate the actual controller into the desired behavior?

Phil Pirozhkov

Mar 30, 2021, 5:11:21 AMMar 30
to Jack Royal-Gordon

It's better done with WebMock, but it depends on what type of test it
is. Is this a feature/system test? Can you set up data in such a way
that this endpoint returns this naturally?
> --
> You received this message because you are subscribed to the Google Groups "rspec" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to
> To view this discussion on the web visit

Jack Royal-Gordon

Mar 30, 2021, 3:42:32 PMMar 30
Hi Phil,

The workaround is to visit the page and then delete a particular db record before triggering the event that causes the JS I’m testing to execute and make the call back to the server. That would result in the “not found” error that I want to test. It’s not as clean as I would like but it would do the job.

Maybe I’m wrong, but I don’t think webmock will work, because it’s set up to intercept web calls from my Rails program, right? In this case, the call will be made from JS running in the browser, so wouldn’t that preclude webmock from intercepting it, or is my understanding about that wrong?

I didn’t actually try webmock, because it’s not currently part of my build.

> To view this discussion on the web visit

Reply all
Reply to author
0 new messages