Ruby on rails 使用Rspec+测试Rails中的错误页面;水豚
在Rails 3.2.9中,我有如下自定义错误页面定义:Ruby on rails 使用Rspec+测试Rails中的错误页面;水豚,ruby-on-rails,ruby,rspec,capybara,Ruby On Rails,Ruby,Rspec,Capybara,在Rails 3.2.9中,我有如下自定义错误页面定义: # application.rb config.exceptions_app = self.routes # routes.rb match '/404' => 'errors#not_found' 这和预期的一样。当我在development.rb中设置config.consived\u all\u requests\u local=false时,我在访问/foo时得到了not\u found视图 但是我如何用Rspec+Ca
# application.rb
config.exceptions_app = self.routes
# routes.rb
match '/404' => 'errors#not_found'
这和预期的一样。当我在development.rb
中设置config.consived\u all\u requests\u local=false时,我在访问/foo
时得到了not\u 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.consulate\u requests\u local=false
,config.consulate\u requests\u 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
test.rb中有问题的设置不仅仅是
consider_all_requests_local = false
而且
config.action_dispatch.show_exceptions = true
如果设置此选项,则应该能够测试错误。
我无法在一个环绕过滤器中使用它
查看一下如果您想这样做并且不想更改config/environments/test.rb
,您可以按照此解决方案进行操作。使用Rails 5.2,Capybara 3 I能够通过以下方式模拟页面错误
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\u dispatch.show\u exceptions=true
,并删除around块 您可以直接访问404错误页面:
访问/404
而不是/foo
我忘了提到,我已经试过在test.rb
中设置考虑所有请求\u local=false
。对我来说,我也有ActionController::RoutingError:谢谢,这正是我所缺少的。我认为问题还不止于此,所以我开始在水豚身上挖掘…控制器规格呢?通过这些更改,我的功能规格可以正常工作,但我仍然在控制器规格中获得失败的测试(带有ActiveRecord::RecordNotFound错误)。是否需要对这些进行其他操作?链接已断开,现在处于打开状态。如果不想在test.rb文件中设置此选项,可以检查此解决方案