我在员工表上定义了一个列“full_name”,该列也设置为不为空。当我运行下面的测试(patent_test.rb)时,我得到下面给出的终端输出。由于我没有针对员工表运行测试,我不明白为什么会出现此错误。
任何人都可以建议为什么当我什至没有在该特定模型上运行测试时我不断收到此错误。
员工表架构
create_table "staffs", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "full_name", null: false
t.string "first_name", null: false
t.string "middle_name"
t.string "last_name", null: false
t.boolean "gender", null: false
t.string "telephone", null: false
t.string "email", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
测试文件(patent_test.rb)
require 'test_helper'
class PatientTest < ActiveSupport::TestCase
test "should not save user without patient" do
patient = Patient.new
assert_not user.save
end
end
终端输出。
rake test
(in /home/user/Rubymine/project1)
Run options: --seed 51365
# Running:
E
Error:
PatientTest#test_should_not_save_user_without_patient:
ActiveRecord::StatementInvalid: Mysql2::Error: Field 'full_name' doesn't have a default value: INSERT INTO `staffs` (`created_at`, `updated_at`, `id`) VALUES ('2017-03-28 08:45:58', '2017-03-28 08:45:58', 980190962)
bin/rails test test/models/patient_test.rb:9
Finished in 0.112169s, 8.9151 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
此外,我的 Staff.rb 文件中仅包含关系和范围(如果有)。
Staff.rb 文件
class Staff < ApplicationRecord
has_one :user
has_many :time_slots
validates_presence_of :full_name
end
内容位于/fixtures/staffs.yml
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
最佳答案
这是因为您已将 Staffs 表上的大多数列声明为 null false 条件。 Rails 在运行每个测试运行之前加载所有固定装置,因此当固定装置“staffs.yml”被命中时,rails 会立即引发错误,因为固定装置有两条记录(一和二)没有数据库所需的值。
你基本上有 3 个选择:
- 删除夹具文件:staffs.yml
- 已注释(在该灯具上的所有行前面给出“#”符号
- 添加所需列,其中包含第一和第二员工的值
关于mysql - 错误:ActiveRecord::StatementInvalid:Mysql2::Error:字段 'full_name' 没有默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43065314/