Rails 3 Tutorial Section 7.3.1 Routing Error
I get the following error when running rspec spec/controllers/users_controller_spec.rb in section 7.3.1 of Michael Hartl's Rails Tutorial:
Failure/Error: get :show, :id => @user
ActionController::RoutingError:
No route matches {:id=>#<User id: 1, #rest is data from the factories.rb file....
Here's my code for the users_controller_spec.rb file:
require 'spec_helper'
require 'factories'
describe UsersController do
render_views
describe "GET 'show'" do
before(:each) do
@user = Factory(:user)
end
it "should be successful" do
get :show, :id => @user
response.should be_success
end
it "should find the right user" do
get :show, :id => @user
assigns(:user).should == @user
end
end
describe "GET 'new'" do
it "should be successful开发者_Go百科" do
get 'new'
response.should be_success
end
it "should have the right title" do
get 'new'
response.should have_selector("title", :content => "Sign up")
end
end
end
Here is my factories.rb code:
Factory.define :user do |user|
user.name "Michael Hartl"
user.email "mhartl@example.com"
user.password "foobar"
user.password_confirmation "foobar"
end
I inserted these lines in Spec_Helper in regards to 'factory_girl':
require 'factory_girl'
Factory.find_definitions
Any idea what's causing the routing error?
Here is my routes.rb code:
SampleApp::Application.routes.draw do
get "users/new"
match '/signup', :to => 'users#new'
match '/contact', :to => 'pages#contact'
match '/about', :to => 'pages#about'
match '/help', :to => 'pages#help'
root :to => 'pages#home'
The author's note regarding using - get :show, :id => @user instead of using - get :show, :id => @user.id:
" Second, note that the value of the hash key :id, instead of being the user’s id attribute @user.id, is the user object itself: get :show, :id => @user
We could use the code: get :show, :id => @user.id to accomplish the same thing, but in this context Rails automatically converts the user object to the corresponding id. It does this by calling the to_param method on the @user variable.
You are missing a route to the show action for users. You can add something like this to the routes.rb file.
match "/users/:id" => "users#show"
If you want the normal CRUD actions, you can get rid of your users/new route and instead of the match line above, just declare them all with a single line:
resources :users
I believe your code is telling Rails that the id is the user, which of course doesn't make sense. That's creating a path like /users/@user, for which no route exists. As you probably know, you want a path like /users/1.
So I think you code should look like
get :show, :id => @user.id
or possibly
get :show, @user
精彩评论