如何用黄瓜测试错误?

时间:2013-11-18 20:16:59

标签: ruby-on-rails ruby testing cucumber

我编写了这个场景来测试当用户访问未发布的条目时,他们会看到错误页面:

Scenario: Unpublished entry
    Given there is an unpublished entry
    When a user visits the entry page
    Then he will see an error page

步骤

Given /^there is (?:an|one) unpublished entry$/ do
  @entry = create(:entry, published: false)
end

When /^a user visits the entry page$/ do
  visit entry_path(@entry)
end

Then(/^he will see an error page$/) do
  expect(response).to raise_error(ActiveRecord::RecordNotFound)
end

运行测试时,它不会超过第二步,因为它失败并出现ActiveRecord::RecordNotFound错误;这就是我想要的,但它发生在错误的一步。

When a user visits the entry page   # features/step_definitions/entry_steps.rb:17
  Couldn't find Entry with id=93 [WHERE "entries"."published" = 't'] (ActiveRecord::RecordNotFound)

显然我做错了什么。如何编写我的场景以更好地表达我的意图,即“访问未发布的条目会引发错误”?

1 个答案:

答案 0 :(得分:2)

如果您向用户返回ActiveRecord::RecordNotFound,则您的网络应用程序存在问题。用户永远不应该看到Rails错误,因为它可以为他们提供有关服务器的敏感信息。另外它看起来很时髦!

这是模式应该是什么:

  1. 用户请求无效项
  2. Rails尝试查找无效项并抛出ActiveRecord::RecordNotFound
  3. Rails捕获ActiveRecord::RecordNotFound并将用户重定向到404页面。
  4. 然后在Cucumber中,你将测试404页面。

    以下是您的启发common HTML error codes的列表。

    修改

    这是抓住ActiveRecord::RecordNotFound错误的好方法。

    class SomeModel
      around_filter :catch_not_found
    
    private
      def catch_not_found
        yield
      rescue
         redirect_to not_found_url
      end
    end
    

    编辑2

    您可能希望返回403 Forbidden而不是404 Not Found

    编辑3

    Here详细讨论了为什么用黄瓜捕捉异常是很奇怪的。这是捕获和重定向的另一个参数。