Most Ruby on Rails developers don’t test their routes, they focus on Model testing, Controller testing, Features or View testing, Helper testing, and try to catch every possible scenarios. I would like to show how to test route separately.
Sample routes.rb:
routes.rb
1
resources:products
Here is routes lists thats have been created:
12345678
root/products#indexpostsGET/products(.:format) products#index POST /products(.:format)products#createnew_postGET/products/new(.:format)products#newedit_postGET/products/:id/edit(.:format)products#editpostGET/products/:id(.:format)products#showPUT/products/:id(.:format)products#updateDELETE/products/:id(.:format)products#destroy
Testing for each routes in routing/products_routing_spec.rb:
require'spec_helper'describe"routing to products"doit"routes /products to products#index"doexpect(get:"/products").toroute_to(controller:"products",action:"index")endit"routes /products/1 to products#show"doexpect(get:"/products/1").toroute_to(controller:"products",action:"show",id:"1")endit"routes /products/new to products#new"doexpect(get:"/products/new").toroute_to(controller:"products",action:"new")endit"routes /products to products#create"doexpect(post:"/products").toroute_to(controller:"products",action:"create")endit"routes /products/1/edit to products#edit"doexpect(get:"/products/1/edit").toroute_to(controller:"products",action:"edit",id:"1")endit"routes /products/1 to products#update"doexpect(put:"/products/1").toroute_to(controller:"products",action:"update",id:"1")endit"routes /products/1 to products#destroy"doexpect(delete:"/products/1").toroute_to(controller:"products",action:"destroy",id:"1")endend
Testing unroutable:
routes.rb
1
resources:products,except:[:show]
products_routing_spec.rb
123
it"does not routes /products/1 to products#show"doexpect(:get=>"posts/1").not_tobe_routableend
So far so good, Let enjoy the routes testing in your Ruby on Rails application. :)