gpt4 book ai didi

ruby-on-rails - 预计 nil 不会成为新记录

转载 作者:行者123 更新时间:2023-11-28 21:13:46 26 4
gpt4 key购买 nike

你好社区我正在做一个简单的应用程序,用户可以注册(作为新用户),所以我试图用我的 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

最佳答案

记录无效,因此未保存。您有一个验证可以防止在没有电子邮件地址的情况下创建记录。

此外,您的创建操作无法从表单中获取输入。

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

关于ruby-on-rails - 预计 nil 不会成为新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com