Jan Krupa
Jan Krupa

Reputation: 506

ActiveRecord::NotNullViolation - Mysql2 Column cannot be null

I run into a problem when creating a record via FactoryBot, the problem only occurs at the test environment.

When I run a command at the development console:

FactoryBot.create(:accounting_pbs_reservation, factor: 3.0) (Column factor is defined at the factories too, but I want to pass it explicitly)

Then it's correctly executed and created, but when I run the command at the test environment, then it prints the error:

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

Even when the factor column is presented.

The problem also occurs when I want to create an instance of the model in RSpec controller.

Did anybody runs into a same problem? The database schema for test and development

The database schema for factor is set as

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

FactoryBot definition is pretty dump:

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

RSpec definition where errors occurs:

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
...

Upvotes: 2

Views: 1436

Answers (1)

Jan Krupa
Jan Krupa

Reputation: 506

So the problem was at the Database trigger.

The triggers sets factor value as null if there is no data in a related table. And the related table is empty because when the test are done, it clears the whole database.

Upvotes: 1

Related Questions