ruby - 使用 Cucumber、Mechanize、Webrat 拯救 HTTP 404 Mechanize::ResponseCodeError 异常

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

我负责使用 Cucumber 测试非 Rails 网络应用程序。我已经启动并运行了基本测试,I.E.我可以做类似的事情

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

接下来我要测试的是不存在的页面,除了显示友好的错误页面外,还会返回正确的 HTTP 响应代码 (404)。

当我在 cucumber 测试期间访问 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 错误页面的正确性?

谢谢。

最佳答案

从您的第一个示例看来您正在使用 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 的 block 语法直接验证响应码:

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

关于ruby - 使用 Cucumber、Mechanize、Webrat 拯救 HTTP 404 Mechanize::ResponseCodeError 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9661669/

相关文章:

ruby - 是否可以从功能文件导航到 VSCode 中的步骤定义

java - 如何将特定的java文件与cucumber中的特定功能文件进行匹配

redirect - TYPO3:404用于限制访问页面而不是登录表单

.htaccess - 404页面返回200 ok

ruby-on-rails - Gems 会减慢 Rails 测试启动速度,我可以有选择地禁用它们吗?

ruby - 检查一个数组是否是 Ruby 中另一个数组的子集

java - 如何整合Spring Boot、Cucumber和Mockito?

ruby - 将 Curl 请求转换为 Net::HTTP 时出错

ruby - 如果 RVM 二进制文件可以作为函数运行,它的用途是什么?

python - Flask 教程 - 404 Not Found