Trouble with RSpec Controller Specs
I had a lot of head scratching just moments ago. Basically it had something to do with controller specs and our in-house plugin ActiveCRUD.
What happens is when you do something like :
context "the Category create page" do
controller_name :categories
specify "should render new if parameters are invalid" do
post :create, :category => valid_category(:name => nil)
response.should render_template(:new)
end
end
You aren’t able to even reach response.should render since doing the post :create will raise the exception.
What happens in our plugin is the same with most of beast-inspired applications. You have code like
def create
@category.attributes = params[:category]
@category.save!
redirect_to category_path
end
private
def rescue_action(exception)
# render invalid model here, etc
end
end
But rSpec happily overrides the controller’s rescue_action method, which means all the expectations we have from our rescue_action are gone.
Right now I did some tweaks to our plugin, catching the exception manually and calling rescue_action_with_validation and then using alias_method_chain.
Hopefully I’ll have a more elegant solution in the future. But hey, they say that tests transform our code into more manageable pieces. I hope that’s what’s happening now.