[rspec-users] How to test for exceptions

Ed Howland ed.howland at gmail.com
Fri Jun 22 18:20:04 EDT 2007

On 5/20/07, Dylan Egan <dylanegan at gmail.com> wrote:
> You want update_attributes! to raise the exception. Otherwise if
> you're returning false you'll want to be using update_attributes and
> if else statements.
> So something like
> it "should ..." do
>   @venue.should_receive(:update_attributes!).with("name" => "random
> text").and_raise(ActiveRecord::RecordInvalid.new(mock_invalid_record))
>   do_update_call
> end
> it "should ..." do
>   do_update_call
>   response.should render_template(:edit)
> end
> This is the mock I create for invalid records.
>  def mock_invalid_record(name = 'invalid_record')
>     invalid_record, errors = mock(name), mock('errors')
>     invalid_record.stub!(:errors).and_return(errors)
>     errors.stub!(:full_messages).and_return(['errors'])
>     invalid_record
>   end

Dylan, I think this code is great. I'd like to recommend that this
should be documented in the RSpec site somehow. If you need to test
controllers that are written in the style of the AWDWR book with save!
and rescue and want to test the save! part and use mocked AR models,
this is definitely the way to go.

Thanks for fixing me. I spent several hours on this till I came across
your post.


Ed Howland
"The information transmitted is intended only for the person or entity
to which it is addressed and may contain proprietary, confidential
and/or legally privileged material. Any review, retransmission,
dissemination or other use of, or taking of any action in reliance
upon, this information by persons or entities other than the intended
recipient is prohibited. If you received this in error, please contact
the sender and delete the material from all computers."

More information about the rspec-users mailing list