1

I was put in charge of testing a non-rails web application using cucumber. I have basic testing up and running, I.E. I can do things like

Then /^the page should have a header$/ do
  response_body.should have_xpath(%\//header\)
end

The next thing I wanted to test is that non-existent pages, in addition to presenting a friendly error page, are returning the correct http response code (404).

When I visit the 404 page during the cucumber test, the following happens.

Scenario: Visit a url which does not lead to a page # features\404.feature:6
    Given I try to visit a fake page                  # features/step_definitions/404_steps.rb:1
      404 => Net::HTTPNotFound (Mechanize::ResponseCodeError)
      ./features/step_definitions/404_steps.rb:2:in `/^I try to visit a fake page$/'
      features\404.feature:7:in `Given I try to visit a fake page'
    When the page loads                               # features/step_definitions/home_steps.rb:5

This makes sense for testing pages that you expect to exist, but I really would like to be able to test my errors as well.

My question is, how can I rescue the Mechanize::ResponseCodeError so that I may verify the correctness of the 404 error page?

Thanks.

1 Answers1

4

From your first example it looks like you're using rspec, so you could use it's assertions to verify the error:

When /^I try to visit a fake page$/ do
    lambda { 
        Mechanize.new.get('http://example.org/fake_page.html')
    }.should raise_error(Mechanize::ResponseCodeError, /404/)
end

Edit: even better, you can use the block syntax of raise_error to verify the response code directly:

.should raise_error{|e| e.response_code.should == '404'}
Jon M
  • 11,669
  • 3
  • 41
  • 47
  • Thanks so much! I had to require mechanize and mechanize/response_code_error in my env.rb to make this work, but now I am able to test the exception. =D – The Shortest Giraffe Mar 12 '12 at 05:44