[rspec-users] Test::Unit Functional failure puzzle

Mark Wilden mark at mwilden.com
Mon Nov 24 11:44:58 EST 2008

On Sun, Nov 23, 2008 at 10:51 AM, Zach Dennis <zach.dennis at gmail.com> wrote:

>  def create
>      @user = User.create! params[:user]
>  rescue ActiveRecord::RecordInvalid
>      # this won't work, because @user never gets assigned, since
> create! raised an exception
>     render :action => "new"
>  end
> In any of the cases where you have to rescue an exception in a
> controller action that will have the same affect of your test not
> reporting the exception. If your application can handle returning a
> default error page to the user then you're probably okay, but if you
> need to re-render something for the user (like the data entry form)
> then you won't want un-rescued exceptions for things like validation
> to occur. And then you may not want to rescue exceptions at all, and
> you might just end back up with #save.

This is just an example of the general principle that one should not use
exception handling for control flow. Exceptions were designed in Ruby (as in
other languages) to handle exception circumstances; in particular, when the
code that causes the problem does not necessarily know how to handle the
problem. Then, exception handling represents a sort of non-local goto. For
unexceptional circumstances (such as a user leaving a form field blank),
exceptions are expensive and harder to understand than simply checking the
return value of a method.

That said, I see lots of code where #save and #create are called without
checking the return value. I don't bother checking the return value when
"nothing could go wrong." But that's what #save! and #create! are for.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20081124/0cdf9fdc/attachment-0001.html>

More information about the rspec-users mailing list