Stub controller action in Rspec controller test, but it's still executed
I would like to test if a controller action is actually called without a redirect happening in some before_filter. Since the controller action itself may do a redirect, I want to stub the action to raise a specific error (SuccessfulActionError or similar) and then check for that error as an indicator that the method was called.
So I added the following:
controller.stub!(:action).and_raise(SuccessfulActionError)
It works somehow, the exception is being raised, but the actual code in the method is still executed (e.g., if I send in the id of a non-existing record to the 'show' action, it throws a ActiveRecord::Record开发者_C百科NotFound exception).
Why is that? I want to completely stub the action as if it was implemented as
def action
raise SuccessfulActionError
end
What am I doing wrong? It this the wrong approach?
EDIT:
Using
controller.should_receive(:action)
doesn't work either.
I overwrite the Controller in a before_all filter like this to fix default_url_options which are not picked up from the ApplicationController:
class MyController
def default_url_options(options = {})
{ :locale => params[:locale] }
end
end
Could that be the culprit? The specs don't work at all when I remove it unfortunately.
It's not clear to me how you can get an ActiveRecord::RecordNotFound exception after stubbing the method. The stub should replace the method call.
As an alternate approach, you might consider setting a message expectation on the action, e.g.
controller.should_receive(:show)
get :show
which should fail if a before_filter prevents the action from being called.
精彩评论