我有一个模式:
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
# Username cannot be null
t.string :username, null: false
t.string :password, null: false
t.string :email, null: false
t.integer :health_record
t.boolean :admin, default: false
t.boolean :activated, default: true
t.timestamps
end
end
end
我尝试运行以下测试:
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(username: 'Bob', password: 'h1l34asi', email: 'loyu@kbu.edu')
end
test 'user creation' do
assert @user.valid?
end
test 'user creation with no username' do
@user.username = nil
# This assertion won't pass!
assert @user.invalid?
end
end
但是我总是会收到此错误:
Failure:
UserTest#test_user_creation_with_no_username [/project/test/models/user_test.rb:15]:
Expected true to be nil or false
在测试之前,我已经尝试了以下方法:
rails db:migrate
rails db:reset
rails db:migrate:reset
doc。
但是它仍然不起作用。为什么?
答案 0 :(得分:1)
"Key 'id' not found in 'LeaveForm'. Choices are: accepted, department, designation, employee_ID, from_date, name, reason, reason_reject, rejected, reporting_manager, to_date, type_of_leave, user."
约束在null: false
级别上有效。尝试将记录保存到数据库中时会出现错误,但是在DB
级别,尽管Model
为username
,该实例仍然有效。
您应该添加验证:
nil