DEV Community

Cover image for Test ALL your static pages in rails with one simple test

Test ALL your static pages in rails with one simple test

samuelfaure profile image Samuel FAURE ・2 min read

What and why

A great friend of mine (who also happens to be a great rails developer) once told me a great trick to increase your code coverage easily. You can just write a test to check if all your GET routes return a non-errored code.

Indeed, the most important information to check about our static GET pages is to know if they are currently erroring or not. So a quick test to check if those pages are working or not is a great low-hanging fruit.

The code itself

To be run with the RSpec framework:

describe Rails.application.routes do
  describe '#get', type: :request do
    # This gets rails routes
    let(:routes_info) { described_class.routes }
    # this select GET routes
    let(:routes_get) { { |r| r.verb == 'GET' } }
    let!(:user) { create(:user) }

    specify 'GET routes returns 200, 301 or 302 code' do
      routes_get.each do |route|
        # parsing routes to a correct uri
        route = route.path.spec.to_s.gsub(/\(.:format\)*$/, '')

        # route_with_params will replace ':security_token' with a test security token
        get route_with_params(route, user)
        expect(response.status).to eq(200).or eq(301).or eq(302)

    def route_with_params(route, user)
      route.gsub!(':security_token', user.security_token)
Enter fullscreen mode Exit fullscreen mode

And that's pretty much it ! As you can see, we just extract all the routes from the Rails application and check that they return a valid code.

There is but one slightly complex point: some of the routes tested might need a parameter, such as a user ID. We use the method route_with_params to inject a user ID in those routes.

Voilà, you might have gotten a great boost to your code coverage with just 20 easy lines of code!

Happy coding to all!

Discussion (2)

Editor guide
coreyja profile image
Corey Alexander

Ooh I love this! I have a similar use case that this might be perfect for!

I have an ActiveAdmin panel that is not as tested as it might like to be lol. But I think sprinkling in this technique to make sure they load would be a great first step! Thanks!

andrewmcodes profile image
Andrew Mason

I really want to dislike this but I think it may be the best code I’ve seen all year. Definitely squirreling this away - thanks for sharing!