简体   繁体   中英

How do I test for an error with cucumber?

I wrote this scenario to test that when a user visits an unpublished entry they will see an error page:

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

Steps

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

When running the test, it does not go past the second step because it fails with an ActiveRecord::RecordNotFound error; this is what I want, but it's happening on the wrong step.

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)

Clearly I'm doing something wrong. How do I write my scenario to better express my intent, which is "visiting an unpublished entry will raise an error"?

There is a problem with your web application if you are returning ActiveRecord::RecordNotFound to a user. Users should never see Rails errors because it could give them sensitive information about your server. Plus it just looks funky!

Here is what the pattern should be:

  1. User requests invalid item
  2. Rails tries to find invalid item and throws ActiveRecord::RecordNotFound
  3. Rails catches ActiveRecord::RecordNotFound and redirects user to 404 page.

Then in Cucumber, you would test for the 404 page.

Here is a list of common HTML error codes for your edification.

EDIT

Here is a great way to catch your ActiveRecord::RecordNotFound errors.

class SomeModel
  around_filter :catch_not_found

private
  def catch_not_found
    yield
  rescue
     redirect_to not_found_url
  end
end

EDIT 2

You may want to return 403 Forbidden instead of 404 Not Found

EDIT 3

Here is a detailed discussion on why catching exceptions with cucumber is weird. This is another argument for catching and redirecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM