Dennis Hackethal
Dennis Hackethal

Reputation: 14275

Custom 404 error routing with rspec

Just stumbled upon this and found the answer while writing the question - since this is a common use case, I thought I'd share it. Until a minute ago, I had the following problem:

I have set up a custom 404 page for my rails application using an errors controller with the following code:

def index
    render "errors/index", status: 404
end

I have set my routes to render this 404 page whenever a route that doesn't exist is accessed:

devise_for :users

get "errors/index", as: :error
get "*not_found", to: "errors#index" # this is the important line

root to: "welcome#index"

And in fact, it does work. For some reason, however, my spec for this doesn't work:

it "renders 404 on unknown route" do
    get("/thisrouteiswrong").should route_to("errors#index")
end

The generated output in the terminal is:

The recognized options <{"controller"=>"errors", "action"=>"index", "not_found"=>"thisrouteiswrong"}> did not match <{"controller"=>"errors", "action"=>"index"}>, difference: <{"not_found"=>"thisrouteiswrong"}>.
   <{"controller"=>"errors", "action"=>"index"}> expected but was
   <{"controller"=>"errors", "action"=>"index", "not_found"=>"thisrouteiswrong"}>.

Upvotes: 0

Views: 1004

Answers (1)

Dennis Hackethal
Dennis Hackethal

Reputation: 14275

As the terminal's error shows, the request has one more parameter called not_found that is set up through the routes. All I had to do was pass that parameter into the test like this:

it "renders 404 on unknown route" do
    get("/thisrouteiswrong").should route_to("errors#index", "not_found" => "thisrouteiswrong")
end

Upvotes: 3

Related Questions