I have written the Users controller and Spec tests correctly for the
“successful creation” in the User controller however I get the
following two errors:
1) UsersController POST 'create' success should create a user
Failure/Error: lambda do
count should have been changed by 1, but was changed by 0
# ./spec/controllers/users_controller_spec.rb:95:in `block (4
levels) in <top (required)>’
2) UsersController POST 'create' success should redirect to the
user show page
Failure/Error: response.should
redirect_to(user_path(assigns(:user)))
ActionController::RoutingError:
No route matches
{:action=>“show”, :controller=>“users”, :id=>#<User id: nil, name:
“New User”, email: “rem[email protected]”, created_at: nil, updated_at:
nil, encrypted_password: nil, salt: nil>}
# ./spec/controllers/users_controller_spec.rb:102:in `block (4
levels) in <top (required)>’
The test specs are as follows:
describe "success" do
before (:each) do
@attr = { :name => "New User" ,
:email => "[email protected]",
:password => "foobar",
:password_confirmation => "foobar"
}
end
it "should create a user" do
lambda do
post :create, :user => @attr
end.should change(User, :count).by(1)
end
it "should redirect to the user show page" do
post :create, :user => @attr
response.should
redirect_to(user_path(assigns(:user)))
end
it "should have a welcome message" do
post :create, :user => @attr
flash[:success].should =~ /welcome to the sample app/
i
end
end
end
The controller code is as follows:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@title = @user.name
end
def new
@user = User.new
@title = "Sign Up"
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to @user, :flash => { :success => "Welcome to the
Sample App!" }
else
@title = “Sign up”
render ‘new’
end
end
end
I’m also getting one new error:
-
UsersController POST ‘create’ success should have a welcome message
Failure/Error: flash[:success].should =~ /welcome to the sample
app/i
expected: /welcome to the sample app/i
got: nil (using =~)./spec/controllers/users_controller_spec.rb:107:in `block (4
levels) in <top (required)>’
Here’s the user model code:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => {:maximum => 50}
validates :email, :presence => true,
:format => {:with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:confirmation => true,
:length => {:within => 6..40}
before_save :encrypt_password
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
class << self
def authenticate(email, submitted_password)
user = User.find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
end
What’s going wrong?