Stubbing/Mocking a controller action in a System Spec

3 views
Skip to first unread message

Jack Royal-Gordon

unread,
Mar 29, 2021, 10:31:13 PMMar 29
to rs...@googlegroups.com
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: #{@book.id}" }

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

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

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 rspec+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/4E901F64-D8F3-45FA-B49B-25E67B7E3988%40pobox.com.

Jack Royal-Gordon

unread,
Mar 30, 2021, 3:42:32 PMMar 30
to rs...@googlegroups.com
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.

Jack
> To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/CAAk5Ok-KUmqi5%2BoZmSHSRB9uGTsk07XkvtHbVWLjF_H%2Bv9dDkg%40mail.gmail.com.

Reply all
Reply to author
Forward
0 new messages