使用Rspec + Capybara在Rails中测试错误页面

在Rails 3.2.9我有自定义错误页面定义如下:

# application.rb config.exceptions_app = self.routes # routes.rb match '/404' => 'errors#not_found' 

哪个效果如预期。 当我在development.rb设置config.consider_all_requests_local = false时,在访问/foo时我得到了not_found视图

但是如何用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" 

我该怎么测试呢?

编辑:

忘了提一下:我在test.rb设置了config.consider_all_requests_local = false

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

 consider_all_requests_local = false 

但是也

 config.action_dispatch.show_exceptions = true 

如果设置此项,您应该能够测试错误。 我无法在周围的filter中使用它。

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

config.consider_all_requests_local = false设置需要在config/environments/test.rb中设置,方法与开发方式相同。

如果您不想对所有测试执行此操作,则可能在测试之前设置状态以及之后的恢复(如下所示):

 # /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 

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

使用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/environments/test.rb设置config.action_dispatch.show_exceptions = true并删除around块。