Read more

RSpec: how to prevent the Rails debug page if you want to actually test for 404s

Klaus Weidinger
October 11, 2021Software engineer at makandra GmbH

Within development and test environments, Rails is usually configured to show a detailed debug page instead of 404s. However, there might be some cases where you expect a 404 and want to test for it.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

An example would be request-specs that check authorization rules. (If you use a gem like consul for managing authorization rules, you should always check these rules via power-specs. However, request-specs can be used as a light-weight version of integration tests here.)

In this case, Rails will replace the 404 page that you want to test for with its debug page. To turn this behaviour off you can use the code from Eliot Sykes' blog post Show archive.org snapshot

I renamed the key realistic_error_responses to true_404s for my projects.

You can then activate the behaviour like this:

describe "Admin Authorization", type: :request do

  describe "GET /admin_panel", :true_404s do
    it "prevents users from accessing the admin area" do
      user = User.create(..., role: :not_an_admin, ...)

      get admin_panel_path(as: user)
      expect(response).to redirect_to_login.or have_http_status(404)
    end
  end
  
end
Posted by Klaus Weidinger to makandra dev (2021-10-11 14:24)