测试404页面已经呈现

时间:2015-11-17 12:21:02

标签: ruby-on-rails rspec

我目前有测试确保某些操作not_routable与rspec

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

但我在rescue_from

中使用ApplicationController更改了处理异常的方式

路线

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'上收到错误,如何在这种情况下模拟帖子请求?

1 个答案:

答案 0 :(得分:2)

请使用Request Specs

您的测试应如下所示:

  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

请注意,此处的帖子不是符号,而是方法调用。