Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dorianmariecom/6b0310aad5746c48974f6a2bb5b214c5 to your computer and use it in GitHub Desktop.
Save dorianmariecom/6b0310aad5746c48974f6a2bb5b214c5 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", github: "rails/rails", branch: "main"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.belongs_to_required_by_default = true
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
end
create_table :comments, force: true do |t|
t.references :post, null: true
end
create_table :views, force: true do |t|
t.references :post
end
end
class Post < ActiveRecord::Base
end
class Comment < ActiveRecord::Base
belongs_to :post, optional: true
end
class View < ActiveRecord::Base
belongs_to :post
end
class BugTest < Minitest::Test
def test_optional_true_with_existing_post_id
post = Post.create!
Comment.create!(post_id: post.id)
end
def test_optional_true_with_no_post_id
Comment.create!
end
def test_optional_true_with_invalid_post_id
assert_raises ActiveRecord::RecordInvalid do
Comment.create!(post_id: 7685453412456)
end
end
def test_with_existing_post_id
post = Post.create!
View.create!(post_id: post.id)
end
def test_with_no_post_id
assert_raises ActiveRecord::RecordInvalid do
View.create!
end
end
def test_with_invalid_post_id
assert_raises ActiveRecord::RecordInvalid do
View.create!(post_id: 7685453412456)
end
end
end
@Flixt
Copy link

Flixt commented Jun 12, 2021

I think somewhere ActiveRecord::Base.belongs_to_required_by_default = true needs to be set for this example to be correct. Otherwise Comment.create! would not raise an error, even if belongs_to :post would require the post to be present.

@dorianmariecom
Copy link
Author

Right, thanks @Flixt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment