测试404页面是否已呈现



我目前有一些测试可以确保某些操作是带有Rspec:的not_routable

it 'does not route to #create' do
  expect(post: '/sectors').to_not be_routable
end
it 'does not route to #show' do
  expect(get: '/sectors/1').to_not be_routable
end

但是,我已经通过在ApplicationController中使用rescue_from来更改处理异常的方式。

路线:

get '*unmatched_route', to: 'application#raise_not_found'

应用控制器:

rescue_from ActiveRecord::RecordNotFound, with: :not_found
rescue_from ActionController::RoutingError, with: :not_found
def not_found
  respond_to do |format|
    format.html { render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found }
    format.xml { head :not_found }
    format.any { head :not_found }
  end
end
def raise_not_found
  raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}")
end

我不太清楚如何构建一个测试来检查404页面及其内容:

it 'does not route to #create' do
    post: '/sectors'
    expect(response.status).to eq(404)
    expect(response).to render_template(:file => "#{Rails.root}/public/404.html")
  end

我在post: '/sectors'上得到一个错误,在这种情况下我如何模拟post请求?

为此使用请求规范。

你的测试应该看起来像:

  it 'does not route to #create' do
    post '/sectors'
    expect(response.status).to eq(404)
    expect(response).to render_template(:file => "#{Rails.root}/public/404.html")
  end

请注意,这里的post不是一个符号,它是一个方法调用。

最新更新