[英]Testing error pages in Rails with Rspec + Capybara
在 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
如果设置此项,则应该能够测试错误。 我无法在周围的过滤器中使用它。
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
如果您想这样做并且不想更改config/environments/test.rb
,则可以按照此帖子中的解决方案进行操作。
使用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块。
您可以直接访问404错误页面:
访问/404
而不是/foo
Rails.application.config
中的变量在测试套件开始时被读取到单独的 hash ( Rails.application.env_config
) - 因此更改特定规范的源变量不起作用。
我能够通过以下围绕块解决这个问题 - 这允许在不影响测试套件的 rest 的情况下测试异常救援
around do |example|
orig_show_exceptions = Rails.application.env_config['action_dispatch.show_exceptions']
orig_detailed_exceptions = Rails.application.env_config['action_dispatch.show_detailed_exceptions']
Rails.application.env_config['action_dispatch.show_exceptions'] = true
Rails.application.env_config['action_dispatch.show_detailed_exceptions'] = false
example.run
Rails.application.env_config['action_dispatch.show_detailed_exceptions'] = orig_detailed_exceptions
Rails.application.env_config['action_dispatch.show_exceptions'] = orig_show_exceptions
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.