你好社区我正在做一个简单的应用程序,用户可以注册(作为新用户),所以我试图用我的Usercontroller创建一个新用户:
class UserController < ApplicationController
def create
@users = User.new
if @users.save
flash[:notice] = 'new user was successfully created.'
redirect_to posts_path
else
render :action => :new
end
end
def new
@user = User.new
end
end
这是我的rspec测试user_controller_spec:
require 'spec/spec_helper'
describe UserController do
it "create new user" do
get :create
assigns[:users].should_not be_new_record
end
end
当我测试它时,它会显示此错误:
故障:
1)UserController创建新用户
Failure/Error: assigns[:users].should_not be_new_record
expected nil not to be a new record
# ./spec/controllers/user_controller_spec.rb:7
以0.15482秒结束 1例,1次失败
最后这里是我的模型
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
has_many :cars
validates_presence_of :email
end
答案 0 :(得分:1)
记录未保存,因为它无效。 您有一个验证可以阻止在没有电子邮件地址的情况下创建记录。
此外,您的创建操作无法从表单中获取输入。
def create
@users = User.new(params[:user]) # the params[:user] is the part you are missing
if @users.save
redirect_to posts_path, :notice => 'new user was successfully created.'
else
render :action => :new
end
end
然后,在测试中,请确保您指定了一个电子邮件地址。
get :create, :user => { :email => 'foo@example.com' }
assigns[:users].should_not be_new_record
答案 1 :(得分:1)
一个问题是:
get :create
Rails的资源路由不会将GET请求路由到create操作,因为create操作会产生副作用。
要测试您需要执行的创建操作:
post :create, "with" => { "some" => "params" }
在测试控制器时,最好拖尾log/test.log
;它会告诉你测试请求在哪里被路由,如果在任何地方。