Test Routes With RSpec in Ruby on Rails

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:

1
2
3
4
5
6
7
8
     root        /                            products#index
    posts GET    /products(.:format)          products#index
          POST   /products(.:format)          products#create
 new_post GET    /products/new(.:format)      products#new
edit_post GET    /products/:id/edit(.:format) products#edit
     post GET    /products/:id(.:format)      products#show
          PUT    /products/:id(.:format)      products#update
          DELETE /products/:id(.:format)      products#destroy

Testing for each routes in routing/products_routing_spec.rb:

products_routing_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
require 'spec_helper'

describe "routing to products" do
  it "routes /products to products#index" do
    expect(get: "/products").to route_to(
      controller: "products",
      action: "index"
    )
  end

  it "routes /products/1 to products#show" do
    expect(get: "/products/1").to route_to(
      controller: "products",
      action: "show",
      id: "1"
    )
  end

  it "routes /products/new to products#new" do
    expect(get: "/products/new").to route_to(
      controller: "products",
      action: "new"
    )
  end

  it "routes /products to products#create" do
    expect(post: "/products").to route_to(
      controller: "products",
      action: "create"
    )
  end

  it "routes /products/1/edit to products#edit" do
    expect(get: "/products/1/edit").to route_to(
      controller: "products",
      action: "edit",
      id: "1"
    )
  end

  it "routes /products/1 to products#update" do
    expect(put: "/products/1").to route_to(
      controller: "products",
      action: "update",
      id: "1"
    )
  end

  it "routes /products/1 to products#destroy" do
    expect(delete: "/products/1").to route_to(
      controller: "products",
      action: "destroy",
      id: "1"
    )
  end
end

Testing unroutable:

routes.rb
1
resources :products, except: [:show]
products_routing_spec.rb
1
2
3
it "does not routes /products/1 to products#show" do
  expect(:get => "posts/1").not_to be_routable
end

So far so good, Let enjoy the routes testing in your Ruby on Rails application. :)