donald
donald

Reputation: 23737

How to test routes with Rspec 2 in Rails 3?

I can't find anything explaining how to test routes in Rails 3. Even in the Rspec book, it doesn't explain well.

Thanks

Upvotes: 17

Views: 9140

Answers (2)

Marnen Laibow-Koser
Marnen Laibow-Koser

Reputation: 6337

Zetetic's answer explains how to test routes. This answer explains why you shouldn't do that.

In general, your tests should test the behavior exposed to the user (or client object), not the implementation by which that behavior is provided. Routes are user-facing: when the user types in http://www.mysite.com/profile, he doesn't care that it goes to ProfilesController; rather, he cares that he sees his profile.

So don't test that you're going to ProfilesController. Rather, set up a Cucumber scenario to test that when the user goes to /profile, he sees his name and profile info. That's all you need.

Again: don't test your routes. Test your behavior.

Upvotes: -8

zetetic
zetetic

Reputation: 47548

There is a brief example on the rspec-rails Github site. You can also use the scaffold generator to produce some canned examples. For instance,

rails g scaffold Article

should produce something like this:

require "spec_helper"

describe ArticlesController do
  describe "routing" do

    it "routes to #index" do
      get("/articles").should route_to("articles#index")
    end

    it "routes to #new" do
      get("/articles/new").should route_to("articles#new")
    end

    it "routes to #show" do
      get("/articles/1").should route_to("articles#show", :id => "1")
    end

    it "routes to #edit" do
      get("/articles/1/edit").should route_to("articles#edit", :id => "1")
    end

    it "routes to #create" do
      post("/articles").should route_to("articles#create")
    end

    it "routes to #update" do
      put("/articles/1").should route_to("articles#update", :id => "1")
    end

    it "routes to #destroy" do
      delete("/articles/1").should route_to("articles#destroy", :id => "1")
    end

  end
end

Upvotes: 32

Related Questions