Skip to content

Instantly share code, notes, and snippets.

@bboe
Last active July 23, 2021 18:45
Show Gist options
  • Save bboe/2d349e2a6d0bed03bfc608e727254154 to your computer and use it in GitHub Desktop.
Save bboe/2d349e2a6d0bed03bfc608e727254154 to your computer and use it in GitHub Desktop.
ActiveModel Validation With Whitespace
#!/usr/bin/env ruby
require 'active_model'
require 'minitest/autorun'
class Simple
include ActiveModel::Model
validates :name, allow_blank: true, allow_nil: true, length: { is: 2 }
attr_accessor :name
# This approach could be fixed by using a `before_validation` method to strip
# whitespace if it's desired to allow the user to accidentally add extraneous
# whitespace.
end
class Precise
include ActiveModel::Model
validates :name, allow_nil: true, format: { with: /\A(\w{2})?\z/ }
attr_accessor :name
end
class TestExample < Minitest::Test
def test_simple
assert_predicate Simple.new(name: nil), :valid?
assert_predicate Simple.new(name: ''), :valid?
assert_predicate Simple.new(name: 'AB'), :valid?
assert_predicate Simple.new(name: 'AB'), :valid?
# The following two cases fall under the `allow_blank` case.
# When the model is backed by ActiveRecord, the whitespace will be saved
# to the database.
assert_predicate Simple.new(name: ' '), :valid?
assert_predicate Simple.new(name: ' '), :valid?
# These are all ones we expect to fail
refute_predicate Simple.new(name: 'A'), :valid?
refute_predicate Simple.new(name: 'ABC'), :valid?
refute_predicate Simple.new(name: 'AB '), :valid?
refute_predicate Simple.new(name: ' AB'), :valid?
# These are unexpected valid cases
assert_predicate Simple.new(name: 'A '), :valid?
assert_predicate Simple.new(name: ' B'), :valid?
end
def test_precise
# These validations are the same as before
assert_predicate Precise.new(name: nil), :valid?
assert_predicate Precise.new(name: ''), :valid?
assert_predicate Precise.new(name: 'AB'), :valid?
assert_predicate Precise.new(name: 'AB'), :valid?
refute_predicate Simple.new(name: 'A'), :valid?
refute_predicate Simple.new(name: 'ABC'), :valid?
refute_predicate Simple.new(name: 'AB '), :valid?
refute_predicate Simple.new(name: ' AB'), :valid?
# These validations differ from before, and are what is expected
refute_predicate Precise.new(name: ' '), :valid?
refute_predicate Precise.new(name: ' '), :valid?
refute_predicate Precise.new(name: 'A '), :valid?
refute_predicate Precise.new(name: ' B'), :valid?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment