使用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

测试中的问题设置。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/

config.consider_all_requests_local = false设置需要在config/environments/test.rb中设置,与您在开发中所做的相同。

如果您不想对所有测试都这样做,也许rspec around过滤器将有用,以便在测试前设置状态并在测试后恢复,如下所示:

# /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,你可以按照这篇文章的解决方案。

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

访问/404而不是/foo

来自Rails.application.config的变量在测试套件开始时被读取到一个单独的散列(Rails.application.env_config) -因此更改特定规范的源变量不起作用。

我可以用下面的around块来解决这个问题——这允许测试异常拯救而不影响测试套件的其余部分

 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

使用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并删除周围块。

相关内容

  • 没有找到相关文章

最新更新