Last active
June 12, 2021 13:30
-
-
Save dorianmariecom/6b0310aad5746c48974f6a2bb5b214c5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think somewhere
ActiveRecord::Base.belongs_to_required_by_default = true
needs to be set for this example to be correct. OtherwiseComment.create!
would not raise an error, even ifbelongs_to :post
would require the post to be present.