Last active
July 26, 2018 14:22
-
-
Save tf/9be6ac3661ba3dfd5608365229d0ac0b to your computer and use it in GitHub Desktop.
Validates presence for null objects broken in Active Record
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 | |
begin | |
require "bundler/inline" | |
rescue LoadError => e | |
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" | |
raise e | |
end | |
gemfile(true) do | |
source "https://rubygems.org" | |
git_source(:github) { |repo| "https://github.com/#{repo}.git" } | |
# Activate the gem you are reporting the issue against. | |
gem "activerecord", "5.2.0" | |
gem "sqlite3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
# Ensure backward compatibility with Minitest 4 | |
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :posts, force: true do |t| | |
end | |
create_table :comments, force: true do |t| | |
t.integer :post_id | |
end | |
end | |
class Post < ActiveRecord::Base | |
has_many :comments | |
end | |
class NullPost | |
def marked_for_destruction? | |
false | |
end | |
def blank? | |
true | |
end | |
end | |
class Comment < ActiveRecord::Base | |
belongs_to :post | |
validates_presence_of :post | |
def post | |
super || NullPost.new | |
end | |
end | |
class CommentWithActiveModelValidation < ActiveRecord::Base | |
self.table_name = 'comments' | |
belongs_to :post | |
validates_with ActiveModel::Validations::PresenceValidator, attributes: [:post] | |
def post | |
super || NullPost.new | |
end | |
end | |
class BugTest < Minitest::Test | |
def test_active_record_presence_validator_handles_null_object | |
comment = Comment.new | |
comment.valid? | |
assert comment.errors[:post].present? | |
end | |
def test_active_model_presence_validator_handles_null_object | |
comment = CommentWithActiveModelValidation.new | |
comment.valid? | |
assert comment.errors[:post].present? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment