ActiveRecord::NotNullViolation - Mysql2 列不能为空

ActiveRecord::NotNullViolation - Mysql2 Column cannot be null

我 运行 在通过 FactoryBot 创建记录时遇到问题,该问题仅出现在 test 环境中。

当我在开发控制台运行命令时:

FactoryBot.create(:accounting_pbs_reservation, factor: 3.0)(工厂也定义了 factor 列,但我想明确传递它)

然后它被正确执行和创建,但是当我 运行 在 test 环境中执行命令时,它会打印错误:

ActiveRecord::NotNullViolation:
  Mysql2::Error: Column 'factor' cannot be null: 
INSERT INTO `accounting_pbs_reservations` (`start`, `rl_walltime`, `factor`) 
VALUES (1503468000, 1430000, 3.0)

即使出现因素列。

当我想在 RSpec 控制器中创建模型实例时也会出现此问题。

有人 运行 遇到同样的问题吗? testdevelopment

的数据库模式

factor 的数据库模式设置为

| Field  | Type   | Null | Key | Default | Extra          
| factor | double | NO   |     | 1       |                

FactoryBot 定义很垃圾:

FactoryBot.define do
  factory :accounting_pbs_reservation do
    factor { 1.0 }
    start { 1_503_468_000 }
    rl_walltime { 1_430_000 }
  end
end

RSpec 发生错误的定义:

require 'rails_helper'

RSpec.describe AccountingPbsReservationsController, type: :controller do
  let(:valid_accounting_pbs_reservation) { FactoryBot.create(:accounting_pbs_reservation) }
  let(:valid_attributes) { FactoryBot.attributes_for(:accounting_pbs_reservation) }

...
    context 'when logged as admin' do
      login_admin
      it "returns a success response" do
        get :show, params: { id: valid_accounting_pbs_reservation.to_param         expect(response).to be_successful
      end
...

所以问题出在数据库触发器上。

如果相关 table 中没有数据,触发器会将 factor 值设置为 null。相关的 table 是空的,因为当测试完成后,它会清除整个数据库。