PG :: UniqueViolation: ОШИБКА в Rails Minitest - PullRequest
0 голосов
/ 23 апреля 2020

Я пережил кошмар в течение 3 дней с этой ошибкой в ​​моем тесте модели приложения rails с использованием Minitest. Приложение и тесты работают нормально на MySql, но я хочу использовать PostgreSql. Тесты часто проходят, но большую часть времени они не проходят. Я прочитал другой связанный пост, но никто из них не дает четких ответов на мою проблему. У меня просто есть простая структура, с которой я хочу начать, как указано ниже:

1. School migration file

class CreateSchools < ActiveRecord::Migration[6.0]
 def change
   create_table :schools do |t|
     t.string :name
     t.string :address
     t.string :email

     t.timestamps
   end
 end
end
2. Billing migration file
class CreateBillings < ActiveRecord::Migration[6.0]
  def change
    create_table :billings do |t|
      t.belongs_to :school, index: true
      t.string :subscription_type, null: false, default: "Monthly"
      t.integer :month_factor, null: false, default: 4
      t.string :status, null: false, default: "Pending"
      t.string :activation_code
      t.timestamps
    end

    add_foreign_key :billings, :schools, on_delete: :cascade

  end
end

3. Term migration file
class CreateTerms < ActiveRecord::Migration[6.0]
  def change
    create_table :terms do |t|
      t.belongs_to :school, index: true
      t.string :session_type, index: true, default: "Term"
      t.string :session_time, index: true, default: "First Term"
      t.string :session_year, index: true, default: 2000
      t.date :begin_date
      t.date :end_date
      t.integer :school_opened
      t.timestamps
    end

    add_foreign_key :terms, :schools, on_delete: :cascade
  end
end

4. Grading scale migration file
class CreateGradingScales < ActiveRecord::Migration[6.0]
  def change
    create_table :grading_scales do |t|
      t.belongs_to :school, index: true
      t.integer :low_mark
      t.integer :high_mark
      t.string :remark
      t.string :grade
      t.string :category

      t.timestamps
    end

    add_foreign_key :grading_scales, :schools, on_delete: :cascade
  end
end

В файлах модели у меня есть следующее:

class School < ApplicationRecord
  has_many :billings
  has_many :terms
  has_many :grading_scales
end

class Billing < ApplicationRecord
  belongs_to :school
end

class Term < ApplicationRecord
  belongs_to :school
end

class GradingScale < ApplicationRecord
  belongs_to :school
end

Я использую крепеж как список ниже для каждой модели

school_1:
  name: "West Hills Academy"
  address: "No. 1 School road"
  email: "info@school_domain.com"
billing_1:
  school: school_1
  subscription_type: Monthly
  month_factor: 4
  status: Starter
  activation_code: Starter
  created_at: <%= DateTime.parse("2016-09-01") %>
  updated_at: <%= DateTime.parse("2016-09-01") %>
term_1:
  school: school_1
  session_type: Terms
  session_time: First Term
  session_year: 2020
  begin_date: "2020-01-01"
  end_date: "2020-20-04"
  school_opened: 180
  created_at: <%= DateTime.iso8601("2016-03-09") %>
  updated_at: <%= DateTime.iso8601("2016-03-09") %>
grading_scale_1:
  school: school_1
  low_mark: 60
  high_mark: 74
  remark: Very Good
  category: Lower
  created_at: <%= DateTime.now %>
  updated_at: <%= DateTime.now %>

grading_scale_2:
  school: school_1
  low_mark: 75
  high_mark: 100
  remark: Excellent
  category: Lower
  created_at: <%= DateTime.now %>
  updated_at: <%= DateTime.now %>

В тесте школьной модели у меня есть это:

require 'test_helper'

class SchoolTest < ActiveSupport::TestCase
  def setup
    @school = schools(:school_1)
  end

  test '#billings' do
    assert @school.billings
  end

  test '#terms' do
    assert @school.terms
  end

  test '#grading_scales' do
    assert @school.grading_scales
  end

end

Когда я бегу the test: rails test test / models / school_test.rb, он проходит, может быть, один или два раза и в большинстве случаев терпит неудачу с этой ошибкой.

ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "billings_pkey"

The ratio of pass to fail is like 1% to 99%.

Я искал в inte rnet причину это но безрезультатно. Я что-то пропустил? Как я уже говорил ранее, он уже работает с настройкой MySql, и я хотел бы использовать PostgreSql для проекта. Тем не менее, поскольку я не могу запустить свой модульный тест, я думаю об использовании MySql, если решение не доступно. Кроме того, я относительно новичок в PostgreSql.

Мне интересно, может ли кто-нибудь дать мне душевное настроение по этому поводу.

Working with:
  Rails 6
  PostgreSql version 12
  Windows 10
...