[rspec-users] Exception handling

David Chelimsky dchelimsky at gmail.com
Wed Jun 30 11:31:39 EDT 2010


On Jun 30, 2010, at 9:29 AM, Marcos Chicote wrote:

> On Wed, Jun 30, 2010 at 11:12 AM, David Chelimsky <dchelimsky at gmail.com> wrote:
> On Jun 30, 2010, at 9:05 AM, Marcos Chicote <totochicote at gmail.com> wrote:
> 
>> I don't think so, but I don't really know how to check it programatically.
>> I don't mean exceptions in before/after methos, but inside it() method
>> 
>> I would like to write something like this:
>> after(:each) do
>> if exception_occured_on_it_method?
>> do_something
>> end
>> end
>> 
>> Is that possible?
> 
> What problem are you trying to solve?
> 
> I'm using rspec to build tests using Watir.
> 
> On before(:each), I create the browser instance and login lazily to a web page (if the browser exists, I use that instance, if it does not, I create a new one). I'm using this lazy approach in order to save the time of openning a new browser and login for each test (I could close the browser on after(:each) but this is faster).
> 
> I most cases (when test are passed), everything works great. The problem is that sometimes the page I'm trying to access doesn't load (or there is some other non functional problem), the browser keeps wating and an timer that I implemented timesout.This timeout raises an exception that makes the test fail, but does not close the browsers windows (that keeps wating for the response), making following tests to fail. 
> 
> If I could handle timeout exception in the way I posted before, I could close the browser and the next test will open a fresh one.
> 
> (Note: this is only and example, there are some other exceptions thay might occur, html element missing for example, that I want to handle the same way and that's why I need a unified mechanism)

There's nothing in RSpec to explicitly handle this for you. There are tools that will likely be available in RSpec-2 by the time we do a final release, but they won't work yet for your goal, so for the short run I think you need to manage this in each example manually. I'd recommend something like:

def capture(exception)
  begin
    yield
  rescue Exception => e
    case e
    if OneType
      # do something
    elsif AnotherType
      # do something different
    end
  end
end

it "..." do
  capture do
    # do stuff
  end
end

It's not perfect, but it should work.

HTH,
David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20100630/d218dc4f/attachment.html>


More information about the rspec-users mailing list