Search code examples
ruby-on-railsrubyrspeccapybaracapybara-webkit

I want to assert for 404 in spec


I want to test my app which redirects to a custom 404, 500 error pages. I turned on config.consider_all_requests_local = false in the test.rb file to check for the error pages. Now everything works fine and I am able to fill in the fields and assert with capybara if the path exists in rake routes eg:

visit signin_path 

the problem is if I give a wrong path like

visit signin_path + '/xyz' #xyz is incorrent

or

visit ('/wrongpage') 

to check for redirection to my custom error page, the test case gives an exception and does not proceed to the expect statement. This is the error:

Failure/Error: visit ('/wrongpage')

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

#then stack trace is printed here

I also tried checking for

expect(page).to raise_error(ActiveRecord::RecordNotFound)

when I try to fetch a record with invalid id (like id = 'xyz' instead of integer, which gives a 500 error), same problem is present here, the execution stops and does not proceeds to the expect statement.

I also tried looking on the internet for answers but didn't get what I was looking for, this (https://stackoverflow.com/a/25469175/2924562) was close but for

visit page_path

gives the following error:

    Failure/Error: visit page_path('wrongpage')

 NoMethodError:
   undefined method `page_path' for ....

Solution

  • Rails.application.config.action_dispatch.show_exceptions
    

    This was the issue!

    It's value should be set as true

    It can be done in two ways, either set it in test.rb file as:

    # Raise exceptions instead of rendering exception templates
      config.action_dispatch.show_exceptions = true
    

    or

      before(:all) do
      Rails.application.config.action_dispatch.show_exceptions = true
      end
    

    Also, don't forget to check this: config.consider_all_requests_local = false, to display your custom error page (in your current environment).