Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# frozen_string_literal: true
require 'rails_helper'
require 'immigrant'
RSpec.describe "assert that no foreign keys are added without constraints", :aggregate_failures do
# These relationships should not be thought of as real FKs
let(:ignored_constraints) { YAML.load(<<~YAML) }
---
- :from_table: some_table
:to_table: other_table
:options:
:column: other_table_id
:primary_key: id
:name: some_table_other_table_id_fk
YAML
it "ensures that no new foreign keys are added without constraints" do
Immigrant.load
Rails.application.eager_load!
keys, warnings = Immigrant::KeyFinder.new.infer_keys
expect(keys.map(&:to_h)).to(match_array(ignored_constraints), -> do
buffer = StringIO.new.tap do |output|
output << "Missing constraints:\n\n"
keys.each do |key|
next if ignored_constraints.include?(key.to_h)
output << "- #{key.from_table}.#{key.options[:column]} to #{key.to_table}.#{key.options[:primary_key]}\n"
end
output << %(\nTo add missing constraints, run 'rails generate immigration [MigrationName]')
end
buffer.string
end)
expect(warnings).to eq(
# These are known and they exists:
%w[some_other_table column_that_looks_like_a_fk] =>
'Skipping some_other_table.column_that_looks_like_a_fk: ' \
'it has multiple associations referencing different keys/tables.',
%w[some_other_table another_column_that_looks_like_a_fk] =>
'Skipping some_other_table.another_column_that_looks_like_a_fk: ' \
'it has multiple associations referencing different keys/tables.',
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.