24

在 Rails 3.2.9 中,我有这样的自定义错误页面定义:

# application.rb
config.exceptions_app = self.routes

# routes.rb
match '/404' => 'errors#not_found'

哪个像预期的那样工作。当我进入时config.consider_all_requests_local = falsedevelopment.rb我会not_found在参观时看到风景/foo

但是如何使用 Rspec + Capybara 进行测试?

我试过这个:

# /spec/features/not_found_spec.rb
require 'spec_helper'
describe 'not found page' do
  it 'should respond with 404 page' do
    visit '/foo'
    page.should have_content('not found')
  end
end

当我运行这个规范时,我得到:

1) not found page should respond with 404 page
  Failure/Error: visit '/foo'
  ActionController::RoutingError:
    No route matches [GET] "/foo"

我该如何测试呢?

编辑:

忘了说:我已经config.consider_all_requests_local = false进去了test.rb

4

5 回答 5

30

test.rb中的问题设置不仅是

consider_all_requests_local = false

但是也

config.action_dispatch.show_exceptions = true

如果你设置了这个,你应该能够测试错误。我无法在周围过滤器中使用它。

看看http://agileleague.com/blog/rails-3-2-custom-error-pages-the-exceptions_app-and-testing-with-capybara/

于 2013-01-03T15:23:55.603 回答
1

config.consider_all_requests_local = false设置需要以config/environments/test.rb与您为开发设置相同的方式进行设置。

如果您不想对所有测试都执行此操作,那么围绕过滤器的 rspec可能有助于在测试之前设置状态并在之后恢复,如下所示:

# /spec/features/not_found_spec.rb
require 'spec_helper'
describe 'not found page' do
  around :each do |example|
     Rails.application.config.consider_all_requests_local = false
     example.run
     Rails.application.config.consider_all_requests_local = true
  end

  it 'should respond with 404 page' do
    visit '/foo'
    page.should have_content('not found')
  end
end
于 2012-12-21T20:19:42.093 回答
1

如果您想这样做并且不想更改config/environments/test.rb,可以按照此帖子中的解决方案进行操作。

于 2015-08-22T14:23:37.457 回答
0

可以直接访问404错误页面:

访问/404而不是/foo

于 2019-07-11T07:59:38.517 回答
-1

使用 Rails 5.2、Capybara 3,我能够使用以下命令模拟页面错误

around do |example|
  Rails.application.config.action_dispatch.show_exceptions = true
  example.run
  Rails.application.config.action_dispatch.show_exceptions = false
end

before do
  allow(Person).to receive(:search).and_raise 'App error simulation!'
end

it 'displays an error message' do
  visit root_path
  fill_in 'q', with: 'anything'
  click_on 'Search'
  expect(page).to have_content 'We are sorry, but the application encountered a problem.'
end

更新

在运行完整的测试套件时,这似乎并不总是有效。所以我不得不设置config.action_dispatch.show_exceptions = trueconfig/environments/test.rb移除周围的块。

于 2018-06-08T14:48:17.360 回答