使用Cucumber,Mechanize,Webrat拯救HTTP 404 Mechanize :: ResponseCodeError异常

时间:2012-03-12 04:15:52

标签: ruby cucumber http-status-code-404 mechanize webrat

我负责使用黄瓜测试非rails web应用程序。我有基本的测试和运行,I.E。我可以做像

这样的事情
Then /^the page should have a header$/ do
  response_body.should have_xpath(%\//header\)
end

我想测试的下一件事是,除了呈现友好的错误页面之外,不存在的页面正在返回正确的http响应代码(404)。

当我在黄瓜测试期间visit 404页面时,会发生以下情况。

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

这对于测试您希望存在的页面是有意义的,但我真的希望能够测试我的错误。

我的问题是,我如何解救Mechanize :: ResponseCodeError以便我可以验证404错误页面的正确性?

感谢。

1 个答案:

答案 0 :(得分:4)

从您的第一个示例看起来您正在使用rspec,因此您可以使用它的断言来验证错误:

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

编辑:更好的是,您可以使用raise_error的块语法直接验证响应代码:

.should raise_error{|e| e.response_code.should == '404'}