DEV Community

Cover image for Test ALL your static pages in rails with one simple test
Samuel-Zacharie FAURE
Samuel-Zacharie FAURE

Posted on • Updated on

Test ALL your static pages in rails with one simple test

Original of this post on my blog.

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) { routes_info.select { |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)
      end
    end

    def route_with_params(route, user)
      route.gsub!(':security_token', user.security_token)
    end
  end
end
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!

Top comments (2)

Collapse
 
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!

Collapse
 
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!