[英]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.