Question: How to test a url which doesn't exist in Rspec?

Question

How to test a url which doesn't exist in Rspec?

Answers 2
Added at 2016-12-28 15:12
Tags
Question

I want to validate that my url in my web application returns 404 Not found. I know it doesn't exist, but I need to confirm that via tests by Rspec. How? This doesn't work:

it "404" do
  get "/some_url_404"
  expect(response.status).to eq 404
end

The test itself fails with:

ActionController::RoutingError: No route matches [GET] "/some_url_404"

update

the answer hasn't been given yet.

Answers
nr: #1 dodano: 2016-12-28 16:12

The most appropriate place for it is request spec (spec/requests subfolder). There the above snippet should work as expected.

nr: #2 dodano: 2016-12-28 17:12

To achieve this, you can create a route to match all paths not defined using this:

get '*path', to: "controller#action"

The controller and action above denote the controller and action you want all requests for routes not listed should go. Here is how the controller action could be

#controller/action

def action
  render(:file => "#{Rails.root}/public/404.html", status: 404)
end

Note

Make sure the route is placed at the bottom of your route. If not, all requests will end there.

Source Show
◀ Wstecz