aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/test
diff options
context:
space:
mode:
Diffstat (limited to 'activemodel/test')
-rw-r--r--activemodel/test/cases/attribute_methods_test.rb281
-rw-r--r--activemodel/test/cases/callbacks_test.rb114
-rw-r--r--activemodel/test/cases/conversion_test.rb50
-rw-r--r--activemodel/test/cases/dirty_test.rb228
-rw-r--r--activemodel/test/cases/errors_test.rb315
-rw-r--r--activemodel/test/cases/forbidden_attributes_protection_test.rb36
-rw-r--r--activemodel/test/cases/helper.rb15
-rw-r--r--activemodel/test/cases/lint_test.rb20
-rw-r--r--activemodel/test/cases/model_test.rb75
-rw-r--r--activemodel/test/cases/naming_test.rb280
-rw-r--r--activemodel/test/cases/railtie_test.rb32
-rw-r--r--activemodel/test/cases/secure_password_test.rb218
-rw-r--r--activemodel/test/cases/serialization_test.rb168
-rw-r--r--activemodel/test/cases/serializers/json_serialization_test.rb215
-rw-r--r--activemodel/test/cases/serializers/xml_serialization_test.rb262
-rw-r--r--activemodel/test/cases/translation_test.rb108
-rw-r--r--activemodel/test/cases/validations/absence_validation_test.rb68
-rw-r--r--activemodel/test/cases/validations/acceptance_validation_test.rb68
-rw-r--r--activemodel/test/cases/validations/callbacks_test.rb98
-rw-r--r--activemodel/test/cases/validations/conditional_validation_test.rb139
-rw-r--r--activemodel/test/cases/validations/confirmation_validation_test.rb108
-rw-r--r--activemodel/test/cases/validations/exclusion_validation_test.rb92
-rw-r--r--activemodel/test/cases/validations/format_validation_test.rb149
-rw-r--r--activemodel/test/cases/validations/i18n_generate_message_validation_test.rb150
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb373
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb147
-rw-r--r--activemodel/test/cases/validations/length_validation_test.rb424
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb211
-rw-r--r--activemodel/test/cases/validations/presence_validation_test.rb107
-rw-r--r--activemodel/test/cases/validations/validates_test.rb159
-rw-r--r--activemodel/test/cases/validations/validations_context_test.rb50
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb172
-rw-r--r--activemodel/test/cases/validations_test.rb392
-rw-r--r--activemodel/test/config.rb3
-rw-r--r--activemodel/test/models/account.rb5
-rw-r--r--activemodel/test/models/blog_post.rb9
-rw-r--r--activemodel/test/models/contact.rb26
-rw-r--r--activemodel/test/models/custom_reader.rb15
-rw-r--r--activemodel/test/models/helicopter.rb7
-rw-r--r--activemodel/test/models/person.rb17
-rw-r--r--activemodel/test/models/person_with_validator.rb24
-rw-r--r--activemodel/test/models/project.rb3
-rw-r--r--activemodel/test/models/reply.rb32
-rw-r--r--activemodel/test/models/sheep.rb3
-rw-r--r--activemodel/test/models/topic.rb40
-rw-r--r--activemodel/test/models/track_back.rb11
-rw-r--r--activemodel/test/models/user.rb10
-rw-r--r--activemodel/test/models/visitor.rb10
-rw-r--r--activemodel/test/validators/email_validator.rb6
-rw-r--r--activemodel/test/validators/namespace/email_validator.rb6
50 files changed, 5551 insertions, 0 deletions
diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb
new file mode 100644
index 0000000000..e81b7ac424
--- /dev/null
+++ b/activemodel/test/cases/attribute_methods_test.rb
@@ -0,0 +1,281 @@
+require 'cases/helper'
+
+class ModelWithAttributes
+ include ActiveModel::AttributeMethods
+
+ class << self
+ define_method(:bar) do
+ 'original bar'
+ end
+ end
+
+ def attributes
+ { foo: 'value of foo', baz: 'value of baz' }
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithAttributes2
+ include ActiveModel::AttributeMethods
+
+ attr_accessor :attributes
+
+ attribute_method_suffix '_test'
+
+private
+ def attribute(name)
+ attributes[name.to_s]
+ end
+
+ alias attribute_test attribute
+
+ def private_method
+ "<3 <3"
+ end
+
+protected
+
+ def protected_method
+ "O_o O_o"
+ end
+end
+
+class ModelWithAttributesWithSpaces
+ include ActiveModel::AttributeMethods
+
+ def attributes
+ { :'foo bar' => 'value of foo bar'}
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithWeirdNamesAttributes
+ include ActiveModel::AttributeMethods
+
+ class << self
+ define_method(:'c?d') do
+ 'original c?d'
+ end
+ end
+
+ def attributes
+ { :'a?b' => 'value of a?b' }
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithRubyKeywordNamedAttributes
+ include ActiveModel::AttributeMethods
+
+ def attributes
+ { begin: 'value of begin', end: 'value of end' }
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
+class ModelWithoutAttributesMethod
+ include ActiveModel::AttributeMethods
+end
+
+class AttributeMethodsTest < ActiveModel::TestCase
+ test 'method missing works correctly even if attributes method is not defined' do
+ assert_raises(NoMethodError) { ModelWithoutAttributesMethod.new.foo }
+ end
+
+ test 'unrelated classes should not share attribute method matchers' do
+ assert_not_equal ModelWithAttributes.send(:attribute_method_matchers),
+ ModelWithAttributes2.send(:attribute_method_matchers)
+ end
+
+ test '#define_attribute_method generates attribute method' do
+ begin
+ ModelWithAttributes.define_attribute_method(:foo)
+
+ assert_respond_to ModelWithAttributes.new, :foo
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ ensure
+ ModelWithAttributes.undefine_attribute_methods
+ end
+ end
+
+ test '#define_attribute_method does not generate attribute method if already defined in attribute module' do
+ klass = Class.new(ModelWithAttributes)
+ klass.generated_attribute_methods.module_eval do
+ def foo
+ '<3'
+ end
+ end
+ klass.define_attribute_method(:foo)
+
+ assert_equal '<3', klass.new.foo
+ end
+
+ test '#define_attribute_method generates a method that is already defined on the host' do
+ klass = Class.new(ModelWithAttributes) do
+ def foo
+ super
+ end
+ end
+ klass.define_attribute_method(:foo)
+
+ assert_equal 'value of foo', klass.new.foo
+ end
+
+ test '#define_attribute_method generates attribute method with invalid identifier characters' do
+ begin
+ ModelWithWeirdNamesAttributes.define_attribute_method(:'a?b')
+
+ assert_respond_to ModelWithWeirdNamesAttributes.new, :'a?b'
+ assert_equal "value of a?b", ModelWithWeirdNamesAttributes.new.send('a?b')
+ ensure
+ ModelWithWeirdNamesAttributes.undefine_attribute_methods
+ end
+ end
+
+ test '#define_attribute_methods works passing multiple arguments' do
+ begin
+ ModelWithAttributes.define_attribute_methods(:foo, :baz)
+
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ assert_equal "value of baz", ModelWithAttributes.new.baz
+ ensure
+ ModelWithAttributes.undefine_attribute_methods
+ end
+ end
+
+ test '#define_attribute_methods generates attribute methods' do
+ begin
+ ModelWithAttributes.define_attribute_methods(:foo)
+
+ assert_respond_to ModelWithAttributes.new, :foo
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ ensure
+ ModelWithAttributes.undefine_attribute_methods
+ end
+ end
+
+ test '#alias_attribute generates attribute_aliases lookup hash' do
+ klass = Class.new(ModelWithAttributes) do
+ define_attribute_methods :foo
+ alias_attribute :bar, :foo
+ end
+
+ assert_equal({ "bar" => "foo" }, klass.attribute_aliases)
+ end
+
+ test '#define_attribute_methods generates attribute methods with spaces in their names' do
+ begin
+ ModelWithAttributesWithSpaces.define_attribute_methods(:'foo bar')
+
+ assert_respond_to ModelWithAttributesWithSpaces.new, :'foo bar'
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.send(:'foo bar')
+ ensure
+ ModelWithAttributesWithSpaces.undefine_attribute_methods
+ end
+ end
+
+ test '#alias_attribute works with attributes with spaces in their names' do
+ begin
+ ModelWithAttributesWithSpaces.define_attribute_methods(:'foo bar')
+ ModelWithAttributesWithSpaces.alias_attribute(:'foo_bar', :'foo bar')
+
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.foo_bar
+ ensure
+ ModelWithAttributesWithSpaces.undefine_attribute_methods
+ end
+ end
+
+ test '#alias_attribute works with attributes named as a ruby keyword' do
+ begin
+ ModelWithRubyKeywordNamedAttributes.define_attribute_methods([:begin, :end])
+ ModelWithRubyKeywordNamedAttributes.alias_attribute(:from, :begin)
+ ModelWithRubyKeywordNamedAttributes.alias_attribute(:to, :end)
+
+ assert_equal "value of begin", ModelWithRubyKeywordNamedAttributes.new.from
+ assert_equal "value of end", ModelWithRubyKeywordNamedAttributes.new.to
+ ensure
+ ModelWithRubyKeywordNamedAttributes.undefine_attribute_methods
+ end
+ end
+
+ test '#undefine_attribute_methods removes attribute methods' do
+ ModelWithAttributes.define_attribute_methods(:foo)
+ ModelWithAttributes.undefine_attribute_methods
+
+ assert !ModelWithAttributes.new.respond_to?(:foo)
+ assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
+ end
+
+ test 'accessing a suffixed attribute' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'foo' => 'bar' }
+
+ assert_equal 'bar', m.foo
+ assert_equal 'bar', m.foo_test
+ end
+
+ test 'should not interfere with method_missing if the attr has a private/protected method' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'private_method' => '<3', 'protected_method' => 'O_o' }
+
+ # dispatches to the *method*, not the attribute
+ assert_equal '<3 <3', m.send(:private_method)
+ assert_equal 'O_o O_o', m.send(:protected_method)
+
+ # sees that a method is already defined, so doesn't intervene
+ assert_raises(NoMethodError) { m.private_method }
+ assert_raises(NoMethodError) { m.protected_method }
+ end
+
+ class ClassWithProtected
+ protected
+ def protected_method
+ end
+ end
+
+ test 'should not interfere with respond_to? if the attribute has a private/protected method' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'private_method' => '<3', 'protected_method' => 'O_o' }
+
+ assert !m.respond_to?(:private_method)
+ assert m.respond_to?(:private_method, true)
+
+ c = ClassWithProtected.new
+
+ # This is messed up, but it's how Ruby works at the moment. Apparently it will be changed
+ # in the future.
+ assert_equal c.respond_to?(:protected_method), m.respond_to?(:protected_method)
+ assert m.respond_to?(:protected_method, true)
+ end
+
+ test 'should use attribute_missing to dispatch a missing attribute' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'foo' => 'bar' }
+
+ def m.attribute_missing(match, *args, &block)
+ match
+ end
+
+ match = m.foo_test
+
+ assert_equal 'foo', match.attr_name
+ assert_equal 'attribute_test', match.target
+ assert_equal 'foo_test', match.method_name
+ end
+end
diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
new file mode 100644
index 0000000000..5fede098d1
--- /dev/null
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -0,0 +1,114 @@
+require "cases/helper"
+
+class CallbacksTest < ActiveModel::TestCase
+
+ class CallbackValidator
+ def around_create(model)
+ model.callbacks << :before_around_create
+ yield
+ model.callbacks << :after_around_create
+ end
+ end
+
+ class ModelCallbacks
+ attr_reader :callbacks
+ extend ActiveModel::Callbacks
+
+ define_model_callbacks :create
+ define_model_callbacks :initialize, only: :after
+ define_model_callbacks :multiple, only: [:before, :around]
+ define_model_callbacks :empty, only: []
+
+ before_create :before_create
+ around_create CallbackValidator.new
+
+ after_create do |model|
+ model.callbacks << :after_create
+ end
+
+ after_create "@callbacks << :final_callback"
+
+ def initialize(valid=true)
+ @callbacks, @valid = [], valid
+ end
+
+ def before_create
+ @callbacks << :before_create
+ end
+
+ def create
+ run_callbacks :create do
+ @callbacks << :create
+ @valid
+ end
+ end
+ end
+
+ test "complete callback chain" do
+ model = ModelCallbacks.new
+ model.create
+ assert_equal model.callbacks, [ :before_create, :before_around_create, :create,
+ :after_around_create, :after_create, :final_callback]
+ end
+
+ test "after callbacks are always appended" do
+ model = ModelCallbacks.new
+ model.create
+ assert_equal model.callbacks.last, :final_callback
+ end
+
+ test "after callbacks are not executed if the block returns false" do
+ model = ModelCallbacks.new(false)
+ model.create
+ assert_equal model.callbacks, [ :before_create, :before_around_create,
+ :create, :after_around_create]
+ end
+
+ test "only selects which types of callbacks should be created" do
+ assert !ModelCallbacks.respond_to?(:before_initialize)
+ assert !ModelCallbacks.respond_to?(:around_initialize)
+ assert_respond_to ModelCallbacks, :after_initialize
+ end
+
+ test "only selects which types of callbacks should be created from an array list" do
+ assert_respond_to ModelCallbacks, :before_multiple
+ assert_respond_to ModelCallbacks, :around_multiple
+ assert !ModelCallbacks.respond_to?(:after_multiple)
+ end
+
+ test "no callbacks should be created" do
+ assert !ModelCallbacks.respond_to?(:before_empty)
+ assert !ModelCallbacks.respond_to?(:around_empty)
+ assert !ModelCallbacks.respond_to?(:after_empty)
+ end
+
+ class Violin
+ attr_reader :history
+ def initialize
+ @history = []
+ end
+ extend ActiveModel::Callbacks
+ define_model_callbacks :create
+ def callback1; self.history << 'callback1'; end
+ def callback2; self.history << 'callback2'; end
+ def create
+ run_callbacks(:create) {}
+ self
+ end
+ end
+ class Violin1 < Violin
+ after_create :callback1, :callback2
+ end
+ class Violin2 < Violin
+ after_create :callback1
+ after_create :callback2
+ end
+
+ test "after_create callbacks with both callbacks declared in one line" do
+ assert_equal ["callback1", "callback2"], Violin1.new.create.history
+ end
+ test "after_create callbacks with both callbacks declared in different lines" do
+ assert_equal ["callback1", "callback2"], Violin2.new.create.history
+ end
+
+end
diff --git a/activemodel/test/cases/conversion_test.rb b/activemodel/test/cases/conversion_test.rb
new file mode 100644
index 0000000000..800cad6d9a
--- /dev/null
+++ b/activemodel/test/cases/conversion_test.rb
@@ -0,0 +1,50 @@
+require 'cases/helper'
+require 'models/contact'
+require 'models/helicopter'
+
+class ConversionTest < ActiveModel::TestCase
+ test "to_model default implementation returns self" do
+ contact = Contact.new
+ assert_equal contact, contact.to_model
+ end
+
+ test "to_key default implementation returns nil for new records" do
+ assert_nil Contact.new.to_key
+ end
+
+ test "to_key default implementation returns the id in an array for persisted records" do
+ assert_equal [1], Contact.new(id: 1).to_key
+ end
+
+ test "to_param default implementation returns nil for new records" do
+ assert_nil Contact.new.to_param
+ end
+
+ test "to_param default implementation returns a string of ids for persisted records" do
+ assert_equal "1", Contact.new(id: 1).to_param
+ end
+
+ test "to_param returns the string joined by '-'" do
+ assert_equal "abc-xyz", Contact.new(id: ["abc", "xyz"]).to_param
+ end
+
+ test "to_param returns nil if to_key is nil" do
+ klass = Class.new(Contact) do
+ def persisted?
+ true
+ end
+ end
+
+ assert_nil klass.new.to_param
+ end
+
+ test "to_partial_path default implementation returns a string giving a relative path" do
+ assert_equal "contacts/contact", Contact.new.to_partial_path
+ assert_equal "helicopters/helicopter", Helicopter.new.to_partial_path,
+ "ActiveModel::Conversion#to_partial_path caching should be class-specific"
+ end
+
+ test "to_partial_path handles namespaced models" do
+ assert_equal "helicopter/comanches/comanche", Helicopter::Comanche.new.to_partial_path
+ end
+end
diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb
new file mode 100644
index 0000000000..db2cd885e2
--- /dev/null
+++ b/activemodel/test/cases/dirty_test.rb
@@ -0,0 +1,228 @@
+require "cases/helper"
+
+class DirtyTest < ActiveModel::TestCase
+ class DirtyModel
+ include ActiveModel::Dirty
+ define_attribute_methods :name, :color, :size
+
+ def initialize
+ @name = nil
+ @color = nil
+ @size = nil
+ end
+
+ def name
+ @name
+ end
+
+ def name=(val)
+ name_will_change!
+ @name = val
+ end
+
+ def color
+ @color
+ end
+
+ def color=(val)
+ color_will_change! unless val == @color
+ @color = val
+ end
+
+ def size
+ @size
+ end
+
+ def size=(val)
+ attribute_will_change!(:size) unless val == @size
+ @size = val
+ end
+
+ def save
+ changes_applied
+ end
+
+ def reload
+ clear_changes_information
+ end
+
+ def deprecated_reload
+ reset_changes
+ end
+ end
+
+ setup do
+ @model = DirtyModel.new
+ end
+
+ test "setting attribute will result in change" do
+ assert !@model.changed?
+ assert !@model.name_changed?
+ @model.name = "Ringo"
+ assert @model.changed?
+ assert @model.name_changed?
+ end
+
+ test "list of changed attribute keys" do
+ assert_equal [], @model.changed
+ @model.name = "Paul"
+ assert_equal ['name'], @model.changed
+ end
+
+ test "changes to attribute values" do
+ assert !@model.changes['name']
+ @model.name = "John"
+ assert_equal [nil, "John"], @model.changes['name']
+ end
+
+ test "checking if an attribute has changed to a particular value" do
+ @model.name = "Ringo"
+ assert @model.name_changed?(from: nil, to: "Ringo")
+ assert_not @model.name_changed?(from: "Pete", to: "Ringo")
+ assert @model.name_changed?(to: "Ringo")
+ assert_not @model.name_changed?(to: "Pete")
+ assert @model.name_changed?(from: nil)
+ assert_not @model.name_changed?(from: "Pete")
+ end
+
+ test "changes accessible through both strings and symbols" do
+ @model.name = "David"
+ assert_not_nil @model.changes[:name]
+ assert_not_nil @model.changes['name']
+ end
+
+ test "be consistent with symbols arguments after the changes are applied" do
+ @model.name = "David"
+ assert @model.attribute_changed?(:name)
+ @model.save
+ @model.name = 'Rafael'
+ assert @model.attribute_changed?(:name)
+ end
+
+ test "attribute mutation" do
+ @model.instance_variable_set("@name", "Yam")
+ assert !@model.name_changed?
+ @model.name.replace("Hadad")
+ assert !@model.name_changed?
+ @model.name_will_change!
+ @model.name.replace("Baal")
+ assert @model.name_changed?
+ end
+
+ test "resetting attribute" do
+ @model.name = "Bob"
+ @model.restore_name!
+ assert_nil @model.name
+ assert !@model.name_changed?
+ end
+
+ test "setting color to same value should not result in change being recorded" do
+ @model.color = "red"
+ assert @model.color_changed?
+ @model.save
+ assert !@model.color_changed?
+ assert !@model.changed?
+ @model.color = "red"
+ assert !@model.color_changed?
+ assert !@model.changed?
+ end
+
+ test "saving should reset model's changed status" do
+ @model.name = "Alf"
+ assert @model.changed?
+ @model.save
+ assert !@model.changed?
+ assert !@model.name_changed?
+ end
+
+ test "saving should preserve previous changes" do
+ @model.name = "Jericho Cane"
+ @model.save
+ assert_equal [nil, "Jericho Cane"], @model.previous_changes['name']
+ end
+
+ test "previous value is preserved when changed after save" do
+ assert_equal({}, @model.changed_attributes)
+ @model.name = "Paul"
+ assert_equal({ "name" => nil }, @model.changed_attributes)
+
+ @model.save
+
+ @model.name = "John"
+ assert_equal({ "name" => "Paul" }, @model.changed_attributes)
+ end
+
+ test "changing the same attribute multiple times retains the correct original value" do
+ @model.name = "Otto"
+ @model.save
+ @model.name = "DudeFella ManGuy"
+ @model.name = "Mr. Manfredgensonton"
+ assert_equal ["Otto", "Mr. Manfredgensonton"], @model.name_change
+ assert_equal @model.name_was, "Otto"
+ end
+
+ test "using attribute_will_change! with a symbol" do
+ @model.size = 1
+ assert @model.size_changed?
+ end
+
+ test "reload should reset all changes" do
+ @model.name = 'Dmitry'
+ @model.name_changed?
+ @model.save
+ @model.name = 'Bob'
+
+ assert_equal [nil, 'Dmitry'], @model.previous_changes['name']
+ assert_equal 'Dmitry', @model.changed_attributes['name']
+
+ @model.reload
+
+ assert_equal ActiveSupport::HashWithIndifferentAccess.new, @model.previous_changes
+ assert_equal ActiveSupport::HashWithIndifferentAccess.new, @model.changed_attributes
+ end
+
+ test "reset_changes is deprecated" do
+ @model.name = 'Dmitry'
+ @model.name_changed?
+ @model.save
+ @model.name = 'Bob'
+
+ assert_equal [nil, 'Dmitry'], @model.previous_changes['name']
+ assert_equal 'Dmitry', @model.changed_attributes['name']
+
+ assert_deprecated do
+ @model.deprecated_reload
+ end
+
+ assert_equal ActiveSupport::HashWithIndifferentAccess.new, @model.previous_changes
+ assert_equal ActiveSupport::HashWithIndifferentAccess.new, @model.changed_attributes
+ end
+
+ test "restore_attributes should restore all previous data" do
+ @model.name = 'Dmitry'
+ @model.color = 'Red'
+ @model.save
+ @model.name = 'Bob'
+ @model.color = 'White'
+
+ @model.restore_attributes
+
+ assert_not @model.changed?
+ assert_equal 'Dmitry', @model.name
+ assert_equal 'Red', @model.color
+ end
+
+ test "restore_attributes can restore only some attributes" do
+ @model.name = 'Dmitry'
+ @model.color = 'Red'
+ @model.save
+ @model.name = 'Bob'
+ @model.color = 'White'
+
+ @model.restore_attributes(['name'])
+
+ assert @model.changed?
+ assert_equal 'Dmitry', @model.name
+ assert_equal 'White', @model.color
+ end
+end
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
new file mode 100644
index 0000000000..42d0365521
--- /dev/null
+++ b/activemodel/test/cases/errors_test.rb
@@ -0,0 +1,315 @@
+require "cases/helper"
+
+class ErrorsTest < ActiveModel::TestCase
+ class Person
+ extend ActiveModel::Naming
+ def initialize
+ @errors = ActiveModel::Errors.new(self)
+ end
+
+ attr_accessor :name, :age
+ attr_reader :errors
+
+ def validate!
+ errors.add(:name, "cannot be nil") if name == nil
+ end
+
+ def read_attribute_for_validation(attr)
+ send(attr)
+ end
+
+ def self.human_attribute_name(attr, options = {})
+ attr
+ end
+
+ def self.lookup_ancestors
+ [self]
+ end
+ end
+
+ def test_delete
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ errors.delete(:foo)
+ assert_empty errors[:foo]
+ end
+
+ def test_include?
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ assert errors.include?(:foo), 'errors should include :foo'
+ end
+
+ def test_dup
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'bar'
+ errors_dup = errors.dup
+ errors_dup[:bar] = 'omg'
+ assert_not_same errors_dup.messages, errors.messages
+ end
+
+ def test_has_key?
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ assert_equal true, errors.has_key?(:foo), 'errors should have key :foo'
+ end
+
+ def test_has_no_key
+ errors = ActiveModel::Errors.new(self)
+ assert_equal false, errors.has_key?(:name), 'errors should not have key :name'
+ end
+
+ test "clear errors" do
+ person = Person.new
+ person.validate!
+
+ assert_equal 1, person.errors.count
+ person.errors.clear
+ assert person.errors.empty?
+ end
+
+ test "get returns the errors for the provided key" do
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = "omg"
+
+ assert_equal ["omg"], errors.get(:foo)
+ end
+
+ test "sets the error with the provided key" do
+ errors = ActiveModel::Errors.new(self)
+ errors.set(:foo, "omg")
+
+ assert_equal({ foo: "omg" }, errors.messages)
+ end
+
+ test "error access is indifferent" do
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = "omg"
+
+ assert_equal ["omg"], errors["foo"]
+ end
+
+ test "values returns an array of messages" do
+ errors = ActiveModel::Errors.new(self)
+ errors.set(:foo, "omg")
+ errors.set(:baz, "zomg")
+
+ assert_equal ["omg", "zomg"], errors.values
+ end
+
+ test "keys returns the error keys" do
+ errors = ActiveModel::Errors.new(self)
+ errors.set(:foo, "omg")
+ errors.set(:baz, "zomg")
+
+ assert_equal [:foo, :baz], errors.keys
+ end
+
+ test "detecting whether there are errors with empty?, blank?, include?" do
+ person = Person.new
+ person.errors[:foo]
+ assert person.errors.empty?
+ assert person.errors.blank?
+ assert !person.errors.include?(:foo)
+ end
+
+ test "adding errors using conditionals with Person#validate!" do
+ person = Person.new
+ person.validate!
+ assert_equal ["name cannot be nil"], person.errors.full_messages
+ assert_equal ["cannot be nil"], person.errors[:name]
+ end
+
+ test "assign error" do
+ person = Person.new
+ person.errors[:name] = 'should not be nil'
+ assert_equal ["should not be nil"], person.errors[:name]
+ end
+
+ test "add an error message on a specific attribute" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ assert_equal ["cannot be blank"], person.errors[:name]
+ end
+
+ test "add an error with a symbol" do
+ person = Person.new
+ person.errors.add(:name, :blank)
+ message = person.errors.generate_message(:name, :blank)
+ assert_equal [message], person.errors[:name]
+ end
+
+ test "add an error with a proc" do
+ person = Person.new
+ message = Proc.new { "cannot be blank" }
+ person.errors.add(:name, message)
+ assert_equal ["cannot be blank"], person.errors[:name]
+ end
+
+ test "added? detects if a specific error was added to the object" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ assert person.errors.added?(:name, "cannot be blank")
+ end
+
+ test "added? handles symbol message" do
+ person = Person.new
+ person.errors.add(:name, :blank)
+ assert person.errors.added?(:name, :blank)
+ end
+
+ test "added? handles proc messages" do
+ person = Person.new
+ message = Proc.new { "cannot be blank" }
+ person.errors.add(:name, message)
+ assert person.errors.added?(:name, message)
+ end
+
+ test "added? defaults message to :invalid" do
+ person = Person.new
+ person.errors.add(:name)
+ assert person.errors.added?(:name)
+ end
+
+ test "added? matches the given message when several errors are present for the same attribute" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ person.errors.add(:name, "is invalid")
+ assert person.errors.added?(:name, "cannot be blank")
+ end
+
+ test "added? returns false when no errors are present" do
+ person = Person.new
+ assert !person.errors.added?(:name)
+ end
+
+ test "added? returns false when checking a nonexisting error and other errors are present for the given attribute" do
+ person = Person.new
+ person.errors.add(:name, "is invalid")
+ assert !person.errors.added?(:name, "cannot be blank")
+ end
+
+ test "size calculates the number of error messages" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ assert_equal 1, person.errors.size
+ end
+
+ test "to_a returns the list of errors with complete messages containing the attribute names" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ person.errors.add(:name, "cannot be nil")
+ assert_equal ["name cannot be blank", "name cannot be nil"], person.errors.to_a
+ end
+
+ test "to_hash returns the error messages hash" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ assert_equal({ name: ["cannot be blank"] }, person.errors.to_hash)
+ end
+
+ test "full_messages creates a list of error messages with the attribute name included" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ person.errors.add(:name, "cannot be nil")
+ assert_equal ["name cannot be blank", "name cannot be nil"], person.errors.full_messages
+ end
+
+ test "full_messages_for contains all the error messages for the given attribute" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ person.errors.add(:name, "cannot be nil")
+ assert_equal ["name cannot be blank", "name cannot be nil"], person.errors.full_messages_for(:name)
+ end
+
+ test "full_messages_for does not contain error messages from other attributes" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ person.errors.add(:email, "cannot be blank")
+ assert_equal ["name cannot be blank"], person.errors.full_messages_for(:name)
+ end
+
+ test "full_messages_for returns an empty list in case there are no errors for the given attribute" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ assert_equal [], person.errors.full_messages_for(:email)
+ end
+
+ test "full_message returns the given message when attribute is :base" do
+ person = Person.new
+ assert_equal "press the button", person.errors.full_message(:base, "press the button")
+ end
+
+ test "full_message returns the given message with the attribute name included" do
+ person = Person.new
+ assert_equal "name cannot be blank", person.errors.full_message(:name, "cannot be blank")
+ assert_equal "name_test cannot be blank", person.errors.full_message(:name_test, "cannot be blank")
+ end
+
+ test "as_json creates a json formatted representation of the errors hash" do
+ person = Person.new
+ person.validate!
+
+ assert_equal({ name: ["cannot be nil"] }, person.errors.as_json)
+ end
+
+ test "as_json with :full_messages option creates a json formatted representation of the errors containing complete messages" do
+ person = Person.new
+ person.validate!
+
+ assert_equal({ name: ["name cannot be nil"] }, person.errors.as_json(full_messages: true))
+ end
+
+ test "generate_message works without i18n_scope" do
+ person = Person.new
+ assert !Person.respond_to?(:i18n_scope)
+ assert_nothing_raised {
+ person.errors.generate_message(:name, :blank)
+ }
+ end
+
+ test "add_on_empty generates message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :empty, {})
+ person.errors.add_on_empty :name
+ end
+
+ test "add_on_empty generates message for multiple attributes" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :empty, {})
+ person.errors.expects(:generate_message).with(:age, :empty, {})
+ person.errors.add_on_empty [:name, :age]
+ end
+
+ test "add_on_empty generates message with custom default message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :empty, { message: 'custom' })
+ person.errors.add_on_empty :name, message: 'custom'
+ end
+
+ test "add_on_empty generates message with empty string value" do
+ person = Person.new
+ person.name = ''
+ person.errors.expects(:generate_message).with(:name, :empty, {})
+ person.errors.add_on_empty :name
+ end
+
+ test "add_on_blank generates message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :blank, {})
+ person.errors.add_on_blank :name
+ end
+
+ test "add_on_blank generates message for multiple attributes" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :blank, {})
+ person.errors.expects(:generate_message).with(:age, :blank, {})
+ person.errors.add_on_blank [:name, :age]
+ end
+
+ test "add_on_blank generates message with custom default message" do
+ person = Person.new
+ person.errors.expects(:generate_message).with(:name, :blank, { message: 'custom' })
+ person.errors.add_on_blank :name, message: 'custom'
+ end
+end
diff --git a/activemodel/test/cases/forbidden_attributes_protection_test.rb b/activemodel/test/cases/forbidden_attributes_protection_test.rb
new file mode 100644
index 0000000000..3cb204a2c5
--- /dev/null
+++ b/activemodel/test/cases/forbidden_attributes_protection_test.rb
@@ -0,0 +1,36 @@
+require 'cases/helper'
+require 'active_support/core_ext/hash/indifferent_access'
+require 'models/account'
+
+class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
+ attr_accessor :permitted
+ alias :permitted? :permitted
+
+ def initialize(attributes)
+ super(attributes)
+ @permitted = false
+ end
+
+ def permit!
+ @permitted = true
+ self
+ end
+end
+
+class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase
+ test "forbidden attributes cannot be used for mass updating" do
+ params = ProtectedParams.new({ "a" => "b" })
+ assert_raises(ActiveModel::ForbiddenAttributesError) do
+ Account.new.sanitize_for_mass_assignment(params)
+ end
+ end
+
+ test "permitted attributes can be used for mass updating" do
+ params = ProtectedParams.new({ "a" => "b" }).permit!
+ assert_equal({ "a" => "b" }, Account.new.sanitize_for_mass_assignment(params))
+ end
+
+ test "regular attributes should still be allowed" do
+ assert_equal({ a: "b" }, Account.new.sanitize_for_mass_assignment(a: "b"))
+ end
+end
diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb
new file mode 100644
index 0000000000..804e0c24f6
--- /dev/null
+++ b/activemodel/test/cases/helper.rb
@@ -0,0 +1,15 @@
+require File.expand_path('../../../../load_paths', __FILE__)
+
+require 'config'
+require 'active_model'
+require 'active_support/core_ext/string/access'
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
+
+# Disable available locale checks to avoid warnings running the test suite.
+I18n.enforce_available_locales = false
+
+require 'active_support/testing/autorun'
+
+require 'mocha/setup' # FIXME: stop using mocha
diff --git a/activemodel/test/cases/lint_test.rb b/activemodel/test/cases/lint_test.rb
new file mode 100644
index 0000000000..8faf93c056
--- /dev/null
+++ b/activemodel/test/cases/lint_test.rb
@@ -0,0 +1,20 @@
+require 'cases/helper'
+
+class LintTest < ActiveModel::TestCase
+ include ActiveModel::Lint::Tests
+
+ class CompliantModel
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ def persisted?() false end
+
+ def errors
+ Hash.new([])
+ end
+ end
+
+ def setup
+ @model = CompliantModel.new
+ end
+end
diff --git a/activemodel/test/cases/model_test.rb b/activemodel/test/cases/model_test.rb
new file mode 100644
index 0000000000..ee0fa26546
--- /dev/null
+++ b/activemodel/test/cases/model_test.rb
@@ -0,0 +1,75 @@
+require 'cases/helper'
+
+class ModelTest < ActiveModel::TestCase
+ include ActiveModel::Lint::Tests
+
+ module DefaultValue
+ def self.included(klass)
+ klass.class_eval { attr_accessor :hello }
+ end
+
+ def initialize(*args)
+ @attr ||= 'default value'
+ super
+ end
+ end
+
+ class BasicModel
+ include DefaultValue
+ include ActiveModel::Model
+ attr_accessor :attr
+ end
+
+ class BasicModelWithReversedMixins
+ include ActiveModel::Model
+ include DefaultValue
+ attr_accessor :attr
+ end
+
+ class SimpleModel
+ include ActiveModel::Model
+ attr_accessor :attr
+ end
+
+ def setup
+ @model = BasicModel.new
+ end
+
+ def test_initialize_with_params
+ object = BasicModel.new(attr: "value")
+ assert_equal "value", object.attr
+ end
+
+ def test_initialize_with_params_and_mixins_reversed
+ object = BasicModelWithReversedMixins.new(attr: "value")
+ assert_equal "value", object.attr
+ end
+
+ def test_initialize_with_nil_or_empty_hash_params_does_not_explode
+ assert_nothing_raised do
+ BasicModel.new()
+ BasicModel.new(nil)
+ BasicModel.new({})
+ SimpleModel.new(attr: 'value')
+ end
+ end
+
+ def test_persisted_is_always_false
+ object = BasicModel.new(attr: "value")
+ assert object.persisted? == false
+ end
+
+ def test_mixin_inclusion_chain
+ object = BasicModel.new
+ assert_equal 'default value', object.attr
+ end
+
+ def test_mixin_initializer_when_args_exist
+ object = BasicModel.new(hello: 'world')
+ assert_equal 'world', object.hello
+ end
+
+ def test_mixin_initializer_when_args_dont_exist
+ assert_raises(NoMethodError) { SimpleModel.new(hello: 'world') }
+ end
+end
diff --git a/activemodel/test/cases/naming_test.rb b/activemodel/test/cases/naming_test.rb
new file mode 100644
index 0000000000..7b8287edbf
--- /dev/null
+++ b/activemodel/test/cases/naming_test.rb
@@ -0,0 +1,280 @@
+require 'cases/helper'
+require 'models/contact'
+require 'models/sheep'
+require 'models/track_back'
+require 'models/blog_post'
+
+class NamingTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Post::TrackBack)
+ end
+
+ def test_singular
+ assert_equal 'post_track_back', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'post_track_backs', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'track_back', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'post/track_backs', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Track back', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'post_track_backs', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'post_track_back', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"post/track_back", @model_name.i18n_key
+ end
+end
+
+class NamingWithNamespacedModelInIsolatedNamespaceTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Blog::Post, Blog)
+ end
+
+ def test_singular
+ assert_equal 'blog_post', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'blog_posts', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'post', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'blog/posts', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Post', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'posts', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'post', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"blog/post", @model_name.i18n_key
+ end
+end
+
+class NamingWithNamespacedModelInSharedNamespaceTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Blog::Post)
+ end
+
+ def test_singular
+ assert_equal 'blog_post', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'blog_posts', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'post', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'blog/posts', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Post', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'blog_posts', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'blog_post', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"blog/post", @model_name.i18n_key
+ end
+end
+
+class NamingWithSuppliedModelNameTest < ActiveModel::TestCase
+ def setup
+ @model_name = ActiveModel::Name.new(Blog::Post, nil, 'Article')
+ end
+
+ def test_singular
+ assert_equal 'article', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'articles', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'article', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'articles', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Article', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'articles', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'article', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"article", @model_name.i18n_key
+ end
+end
+
+class NamingUsingRelativeModelNameTest < ActiveModel::TestCase
+ def setup
+ @model_name = Blog::Post.model_name
+ end
+
+ def test_singular
+ assert_equal 'blog_post', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'blog_posts', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'post', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'blog/posts', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Post', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'posts', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'post', @model_name.param_key
+ end
+
+ def test_i18n_key
+ assert_equal :"blog/post", @model_name.i18n_key
+ end
+end
+
+class NamingHelpersTest < ActiveModel::TestCase
+ def setup
+ @klass = Contact
+ @record = @klass.new
+ @singular = 'contact'
+ @plural = 'contacts'
+ @uncountable = Sheep
+ @singular_route_key = 'contact'
+ @route_key = 'contacts'
+ @param_key = 'contact'
+ end
+
+ def test_to_model_called_on_record
+ assert_equal 'post_named_track_backs', plural(Post::TrackBack.new)
+ end
+
+ def test_singular
+ assert_equal @singular, singular(@record)
+ end
+
+ def test_singular_for_class
+ assert_equal @singular, singular(@klass)
+ end
+
+ def test_plural
+ assert_equal @plural, plural(@record)
+ end
+
+ def test_plural_for_class
+ assert_equal @plural, plural(@klass)
+ end
+
+ def test_route_key
+ assert_equal @route_key, route_key(@record)
+ assert_equal @singular_route_key, singular_route_key(@record)
+ end
+
+ def test_route_key_for_class
+ assert_equal @route_key, route_key(@klass)
+ assert_equal @singular_route_key, singular_route_key(@klass)
+ end
+
+ def test_param_key
+ assert_equal @param_key, param_key(@record)
+ end
+
+ def test_param_key_for_class
+ assert_equal @param_key, param_key(@klass)
+ end
+
+ def test_uncountable
+ assert uncountable?(@uncountable), "Expected 'sheep' to be uncountable"
+ assert !uncountable?(@klass), "Expected 'contact' to be countable"
+ end
+
+ def test_uncountable_route_key
+ assert_equal "sheep", singular_route_key(@uncountable)
+ assert_equal "sheep_index", route_key(@uncountable)
+ end
+
+ private
+ def method_missing(method, *args)
+ ActiveModel::Naming.send(method, *args)
+ end
+end
+
+class NameWithAnonymousClassTest < ActiveModel::TestCase
+ def test_anonymous_class_without_name_argument
+ assert_raises(ArgumentError) do
+ ActiveModel::Name.new(Class.new)
+ end
+ end
+
+ def test_anonymous_class_with_name_argument
+ model_name = ActiveModel::Name.new(Class.new, nil, "Anonymous")
+ assert_equal "Anonymous", model_name
+ end
+end
+
+class NamingMethodDelegationTest < ActiveModel::TestCase
+ def test_model_name
+ assert_equal Blog::Post.model_name, Blog::Post.new.model_name
+ end
+end
diff --git a/activemodel/test/cases/railtie_test.rb b/activemodel/test/cases/railtie_test.rb
new file mode 100644
index 0000000000..96b3b07e50
--- /dev/null
+++ b/activemodel/test/cases/railtie_test.rb
@@ -0,0 +1,32 @@
+require 'cases/helper'
+require 'active_support/testing/isolation'
+
+class RailtieTest < ActiveModel::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ require 'active_model/railtie'
+
+ # Set a fake logger to avoid creating the log directory automatically
+ fake_logger = Logger.new(nil)
+
+ @app ||= Class.new(::Rails::Application) do
+ config.eager_load = false
+ config.logger = fake_logger
+ end
+ end
+
+ test 'secure password min_cost is false in the development environment' do
+ Rails.env = 'development'
+ @app.initialize!
+
+ assert_equal false, ActiveModel::SecurePassword.min_cost
+ end
+
+ test 'secure password min_cost is true in the test environment' do
+ Rails.env = 'test'
+ @app.initialize!
+
+ assert_equal true, ActiveModel::SecurePassword.min_cost
+ end
+end
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
new file mode 100644
index 0000000000..6d56c8344a
--- /dev/null
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -0,0 +1,218 @@
+require 'cases/helper'
+require 'models/user'
+require 'models/visitor'
+
+class SecurePasswordTest < ActiveModel::TestCase
+ setup do
+ # Used only to speed up tests
+ @original_min_cost = ActiveModel::SecurePassword.min_cost
+ ActiveModel::SecurePassword.min_cost = true
+
+ @user = User.new
+ @visitor = Visitor.new
+
+ # Simulate loading an existing user from the DB
+ @existing_user = User.new
+ @existing_user.password_digest = BCrypt::Password.create('password', cost: BCrypt::Engine::MIN_COST)
+ end
+
+ teardown do
+ ActiveModel::SecurePassword.min_cost = @original_min_cost
+ end
+
+ test "automatically include ActiveModel::Validations when validations are enabled" do
+ assert_respond_to @user, :valid?
+ end
+
+ test "don't include ActiveModel::Validations when validations are disabled" do
+ assert_not_respond_to @visitor, :valid?
+ end
+
+ test "create a new user with validations and valid password/confirmation" do
+ @user.password = 'password'
+ @user.password_confirmation = 'password'
+
+ assert @user.valid?(:create), 'user should be valid'
+
+ @user.password = 'a' * 72
+ @user.password_confirmation = 'a' * 72
+
+ assert @user.valid?(:create), 'user should be valid'
+ end
+
+ test "create a new user with validation and a spaces only password" do
+ @user.password = ' ' * 72
+ assert @user.valid?(:create), 'user should be valid'
+ end
+
+ test "create a new user with validation and a blank password" do
+ @user.password = ''
+ assert !@user.valid?(:create), 'user should be invalid'
+ assert_equal 1, @user.errors.count
+ assert_equal ["can't be blank"], @user.errors[:password]
+ end
+
+ test "create a new user with validation and a nil password" do
+ @user.password = nil
+ assert !@user.valid?(:create), 'user should be invalid'
+ assert_equal 1, @user.errors.count
+ assert_equal ["can't be blank"], @user.errors[:password]
+ end
+
+ test 'create a new user with validation and password length greater than 72' do
+ @user.password = 'a' * 73
+ @user.password_confirmation = 'a' * 73
+ assert !@user.valid?(:create), 'user should be invalid'
+ assert_equal 1, @user.errors.count
+ assert_equal ["is too long (maximum is 72 characters)"], @user.errors[:password]
+ end
+
+ test "create a new user with validation and a blank password confirmation" do
+ @user.password = 'password'
+ @user.password_confirmation = ''
+ assert !@user.valid?(:create), 'user should be invalid'
+ assert_equal 1, @user.errors.count
+ assert_equal ["doesn't match Password"], @user.errors[:password_confirmation]
+ end
+
+ test "create a new user with validation and a nil password confirmation" do
+ @user.password = 'password'
+ @user.password_confirmation = nil
+ assert @user.valid?(:create), 'user should be valid'
+ end
+
+ test "create a new user with validation and an incorrect password confirmation" do
+ @user.password = 'password'
+ @user.password_confirmation = 'something else'
+ assert !@user.valid?(:create), 'user should be invalid'
+ assert_equal 1, @user.errors.count
+ assert_equal ["doesn't match Password"], @user.errors[:password_confirmation]
+ end
+
+ test "update an existing user with validation and no change in password" do
+ assert @existing_user.valid?(:update), 'user should be valid'
+ end
+
+ test "update an existing user with validations and valid password/confirmation" do
+ @existing_user.password = 'password'
+ @existing_user.password_confirmation = 'password'
+
+ assert @existing_user.valid?(:update), 'user should be valid'
+
+ @existing_user.password = 'a' * 72
+ @existing_user.password_confirmation = 'a' * 72
+
+ assert @existing_user.valid?(:update), 'user should be valid'
+ end
+
+ test "updating an existing user with validation and a blank password" do
+ @existing_user.password = ''
+ assert @existing_user.valid?(:update), 'user should be valid'
+ end
+
+ test "updating an existing user with validation and a spaces only password" do
+ @user.password = ' ' * 72
+ assert @user.valid?(:update), 'user should be valid'
+ end
+
+ test "updating an existing user with validation and a blank password and password_confirmation" do
+ @existing_user.password = ''
+ @existing_user.password_confirmation = ''
+ assert @existing_user.valid?(:update), 'user should be valid'
+ end
+
+ test "updating an existing user with validation and a nil password" do
+ @existing_user.password = nil
+ assert !@existing_user.valid?(:update), 'user should be invalid'
+ assert_equal 1, @existing_user.errors.count
+ assert_equal ["can't be blank"], @existing_user.errors[:password]
+ end
+
+ test 'updating an existing user with validation and password length greater than 72' do
+ @existing_user.password = 'a' * 73
+ @existing_user.password_confirmation = 'a' * 73
+ assert !@existing_user.valid?(:update), 'user should be invalid'
+ assert_equal 1, @existing_user.errors.count
+ assert_equal ["is too long (maximum is 72 characters)"], @existing_user.errors[:password]
+ end
+
+ test "updating an existing user with validation and a blank password confirmation" do
+ @existing_user.password = 'password'
+ @existing_user.password_confirmation = ''
+ assert !@existing_user.valid?(:update), 'user should be invalid'
+ assert_equal 1, @existing_user.errors.count
+ assert_equal ["doesn't match Password"], @existing_user.errors[:password_confirmation]
+ end
+
+ test "updating an existing user with validation and a nil password confirmation" do
+ @existing_user.password = 'password'
+ @existing_user.password_confirmation = nil
+ assert @existing_user.valid?(:update), 'user should be valid'
+ end
+
+ test "updating an existing user with validation and an incorrect password confirmation" do
+ @existing_user.password = 'password'
+ @existing_user.password_confirmation = 'something else'
+ assert !@existing_user.valid?(:update), 'user should be invalid'
+ assert_equal 1, @existing_user.errors.count
+ assert_equal ["doesn't match Password"], @existing_user.errors[:password_confirmation]
+ end
+
+ test "updating an existing user with validation and a blank password digest" do
+ @existing_user.password_digest = ''
+ assert !@existing_user.valid?(:update), 'user should be invalid'
+ assert_equal 1, @existing_user.errors.count
+ assert_equal ["can't be blank"], @existing_user.errors[:password]
+ end
+
+ test "updating an existing user with validation and a nil password digest" do
+ @existing_user.password_digest = nil
+ assert !@existing_user.valid?(:update), 'user should be invalid'
+ assert_equal 1, @existing_user.errors.count
+ assert_equal ["can't be blank"], @existing_user.errors[:password]
+ end
+
+ test "setting a blank password should not change an existing password" do
+ @existing_user.password = ''
+ assert @existing_user.password_digest == 'password'
+ end
+
+ test "setting a nil password should clear an existing password" do
+ @existing_user.password = nil
+ assert_equal nil, @existing_user.password_digest
+ end
+
+ test "authenticate" do
+ @user.password = "secret"
+
+ assert !@user.authenticate("wrong")
+ assert @user.authenticate("secret")
+ end
+
+ test "Password digest cost defaults to bcrypt default cost when min_cost is false" do
+ ActiveModel::SecurePassword.min_cost = false
+
+ @user.password = "secret"
+ assert_equal BCrypt::Engine::DEFAULT_COST, @user.password_digest.cost
+ end
+
+ test "Password digest cost honors bcrypt cost attribute when min_cost is false" do
+ begin
+ original_bcrypt_cost = BCrypt::Engine.cost
+ ActiveModel::SecurePassword.min_cost = false
+ BCrypt::Engine.cost = 5
+
+ @user.password = "secret"
+ assert_equal BCrypt::Engine.cost, @user.password_digest.cost
+ ensure
+ BCrypt::Engine.cost = original_bcrypt_cost
+ end
+ end
+
+ test "Password digest cost can be set to bcrypt min cost to speed up tests" do
+ ActiveModel::SecurePassword.min_cost = true
+
+ @user.password = "secret"
+ assert_equal BCrypt::Engine::MIN_COST, @user.password_digest.cost
+ end
+end
diff --git a/activemodel/test/cases/serialization_test.rb b/activemodel/test/cases/serialization_test.rb
new file mode 100644
index 0000000000..4ae41aa19c
--- /dev/null
+++ b/activemodel/test/cases/serialization_test.rb
@@ -0,0 +1,168 @@
+require "cases/helper"
+require 'active_support/core_ext/object/instance_variables'
+
+class SerializationTest < ActiveModel::TestCase
+ class User
+ include ActiveModel::Serialization
+
+ attr_accessor :name, :email, :gender, :address, :friends
+
+ def initialize(name, email, gender)
+ @name, @email, @gender = name, email, gender
+ @friends = []
+ end
+
+ def attributes
+ instance_values.except("address", "friends")
+ end
+
+ def foo
+ 'i_am_foo'
+ end
+ end
+
+ class Address
+ include ActiveModel::Serialization
+
+ attr_accessor :street, :city, :state, :zip
+
+ def attributes
+ instance_values
+ end
+ end
+
+ setup do
+ @user = User.new('David', 'david@example.com', 'male')
+ @user.address = Address.new
+ @user.address.street = "123 Lane"
+ @user.address.city = "Springfield"
+ @user.address.state = "CA"
+ @user.address.zip = 11111
+ @user.friends = [User.new('Joe', 'joe@example.com', 'male'),
+ User.new('Sue', 'sue@example.com', 'female')]
+ end
+
+ def test_method_serializable_hash_should_work
+ expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"}
+ assert_equal expected, @user.serializable_hash
+ end
+
+ def test_method_serializable_hash_should_work_with_only_option
+ expected = {"name"=>"David"}
+ assert_equal expected, @user.serializable_hash(only: [:name])
+ end
+
+ def test_method_serializable_hash_should_work_with_except_option
+ expected = {"gender"=>"male", "email"=>"david@example.com"}
+ assert_equal expected, @user.serializable_hash(except: [:name])
+ end
+
+ def test_method_serializable_hash_should_work_with_methods_option
+ expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "email"=>"david@example.com"}
+ assert_equal expected, @user.serializable_hash(methods: [:foo])
+ end
+
+ def test_method_serializable_hash_should_work_with_only_and_methods
+ expected = {"foo"=>"i_am_foo"}
+ assert_equal expected, @user.serializable_hash(only: [], methods: [:foo])
+ end
+
+ def test_method_serializable_hash_should_work_with_except_and_methods
+ expected = {"gender"=>"male", "foo"=>"i_am_foo"}
+ assert_equal expected, @user.serializable_hash(except: [:name, :email], methods: [:foo])
+ end
+
+ def test_should_not_call_methods_that_dont_respond
+ expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"}
+ assert_equal expected, @user.serializable_hash(methods: [:bar])
+ end
+
+ def test_should_use_read_attribute_for_serialization
+ def @user.read_attribute_for_serialization(n)
+ "Jon"
+ end
+
+ expected = { "name" => "Jon" }
+ assert_equal expected, @user.serializable_hash(only: :name)
+ end
+
+ def test_include_option_with_singular_association
+ expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com",
+ "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}}
+ assert_equal expected, @user.serializable_hash(include: :address)
+ end
+
+ def test_include_option_with_plural_association
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
+ assert_equal expected, @user.serializable_hash(include: :friends)
+ end
+
+ def test_include_option_with_empty_association
+ @user.friends = []
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", "friends"=>[]}
+ assert_equal expected, @user.serializable_hash(include: :friends)
+ end
+
+ class FriendList
+ def initialize(friends)
+ @friends = friends
+ end
+
+ def to_ary
+ @friends
+ end
+ end
+
+ def test_include_option_with_ary
+ @user.friends = FriendList.new(@user.friends)
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
+ assert_equal expected, @user.serializable_hash(include: :friends)
+ end
+
+ def test_multiple_includes
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111},
+ "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
+ assert_equal expected, @user.serializable_hash(include: [:address, :friends])
+ end
+
+ def test_include_with_options
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{"street"=>"123 Lane"}}
+ assert_equal expected, @user.serializable_hash(include: { address: { only: "street" } })
+ end
+
+ def test_nested_include
+ @user.friends.first.friends = [@user]
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male',
+ "friends"=> [{"email"=>"david@example.com", "gender"=>"male", "name"=>"David"}]},
+ {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female', "friends"=> []}]}
+ assert_equal expected, @user.serializable_hash(include: { friends: { include: :friends } })
+ end
+
+ def test_only_include
+ expected = {"name"=>"David", "friends" => [{"name" => "Joe"}, {"name" => "Sue"}]}
+ assert_equal expected, @user.serializable_hash(only: :name, include: { friends: { only: :name } })
+ end
+
+ def test_except_include
+ expected = {"name"=>"David", "email"=>"david@example.com",
+ "friends"=> [{"name" => 'Joe', "email" => 'joe@example.com'},
+ {"name" => "Sue", "email" => 'sue@example.com'}]}
+ assert_equal expected, @user.serializable_hash(except: :gender, include: { friends: { except: :gender } })
+ end
+
+ def test_multiple_includes_with_options
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{"street"=>"123 Lane"},
+ "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
+ assert_equal expected, @user.serializable_hash(include: [{ address: {only: "street" } }, :friends])
+ end
+end
diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb
new file mode 100644
index 0000000000..734656b749
--- /dev/null
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -0,0 +1,215 @@
+require 'cases/helper'
+require 'models/contact'
+require 'active_support/core_ext/object/instance_variables'
+
+class Contact
+ include ActiveModel::Serializers::JSON
+ include ActiveModel::Validations
+
+ def attributes=(hash)
+ hash.each do |k, v|
+ instance_variable_set("@#{k}", v)
+ end
+ end
+
+ remove_method :attributes if method_defined?(:attributes)
+
+ def attributes
+ instance_values
+ end
+end
+
+class JsonSerializationTest < ActiveModel::TestCase
+ def setup
+ @contact = Contact.new
+ @contact.name = 'Konata Izumi'
+ @contact.age = 16
+ @contact.created_at = Time.utc(2006, 8, 1)
+ @contact.awesome = true
+ @contact.preferences = { 'shows' => 'anime' }
+ end
+
+ test "should not include root in json (class method)" do
+ json = @contact.to_json
+
+ assert_no_match %r{^\{"contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should include root in json if include_root_in_json is true" do
+ begin
+ original_include_root_in_json = Contact.include_root_in_json
+ Contact.include_root_in_json = true
+ json = @contact.to_json
+
+ assert_match %r{^\{"contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ ensure
+ Contact.include_root_in_json = original_include_root_in_json
+ end
+ end
+
+ test "should include root in json (option) even if the default is set to false" do
+ json = @contact.to_json(root: true)
+
+ assert_match %r{^\{"contact":\{}, json
+ end
+
+ test "should not include root in json (option)" do
+ json = @contact.to_json(root: false)
+
+ assert_no_match %r{^\{"contact":\{}, json
+ end
+
+ test "should include custom root in json" do
+ json = @contact.to_json(root: 'json_contact')
+
+ assert_match %r{^\{"json_contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should encode all encodable attributes" do
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should allow attribute filtering with only" do
+ json = @contact.to_json(only: [:name, :age])
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert_no_match %r{"awesome":true}, json
+ assert !json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_no_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "should allow attribute filtering with except" do
+ json = @contact.to_json(except: [:name, :age])
+
+ assert_no_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{"age":16}, json
+ assert_match %r{"awesome":true}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
+ end
+
+ test "methods are called on object" do
+ # Define methods on fixture.
+ def @contact.label; "Has cheezburger"; end
+ def @contact.favorite_quote; "Constraints are liberating"; end
+
+ # Single method.
+ assert_match %r{"label":"Has cheezburger"}, @contact.to_json(only: :name, methods: :label)
+
+ # Both methods.
+ methods_json = @contact.to_json(only: :name, methods: [:label, :favorite_quote])
+ assert_match %r{"label":"Has cheezburger"}, methods_json
+ assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
+ end
+
+ test "should return Hash for errors" do
+ contact = Contact.new
+ contact.errors.add :name, "can't be blank"
+ contact.errors.add :name, "is too short (minimum is 2 characters)"
+ contact.errors.add :age, "must be 16 or over"
+
+ hash = {}
+ hash[:name] = ["can't be blank", "is too short (minimum is 2 characters)"]
+ hash[:age] = ["must be 16 or over"]
+ assert_equal hash.to_json, contact.errors.to_json
+ end
+
+ test "serializable_hash should not modify options passed in argument" do
+ options = { except: :name }
+ @contact.serializable_hash(options)
+
+ assert_nil options[:only]
+ assert_equal :name, options[:except]
+ end
+
+ test "as_json should return a hash if include_root_in_json is true" do
+ begin
+ original_include_root_in_json = Contact.include_root_in_json
+ Contact.include_root_in_json = true
+ json = @contact.as_json
+
+ assert_kind_of Hash, json
+ assert_kind_of Hash, json['contact']
+ %w(name age created_at awesome preferences).each do |field|
+ assert_equal @contact.send(field), json['contact'][field]
+ end
+ ensure
+ Contact.include_root_in_json = original_include_root_in_json
+ end
+ end
+
+ test "from_json should work without a root (class attribute)" do
+ json = @contact.to_json
+ result = Contact.new.from_json(json)
+
+ assert_equal result.name, @contact.name
+ assert_equal result.age, @contact.age
+ assert_equal Time.parse(result.created_at), @contact.created_at
+ assert_equal result.awesome, @contact.awesome
+ assert_equal result.preferences, @contact.preferences
+ end
+
+ test "from_json should work without a root (method parameter)" do
+ json = @contact.to_json
+ result = Contact.new.from_json(json, false)
+
+ assert_equal result.name, @contact.name
+ assert_equal result.age, @contact.age
+ assert_equal Time.parse(result.created_at), @contact.created_at
+ assert_equal result.awesome, @contact.awesome
+ assert_equal result.preferences, @contact.preferences
+ end
+
+ test "from_json should work with a root (method parameter)" do
+ json = @contact.to_json(root: :true)
+ result = Contact.new.from_json(json, true)
+
+ assert_equal result.name, @contact.name
+ assert_equal result.age, @contact.age
+ assert_equal Time.parse(result.created_at), @contact.created_at
+ assert_equal result.awesome, @contact.awesome
+ assert_equal result.preferences, @contact.preferences
+ end
+
+ test "custom as_json should be honored when generating json" do
+ def @contact.as_json(options); { name: name, created_at: created_at }; end
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}}, json
+ assert_no_match %r{"awesome":}, json
+ assert_no_match %r{"preferences":}, json
+ end
+
+ test "custom as_json options should be extensible" do
+ def @contact.as_json(options = {}); super(options.merge(only: [:name])); end
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{"created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}}, json
+ assert_no_match %r{"awesome":}, json
+ assert_no_match %r{"preferences":}, json
+ end
+end
diff --git a/activemodel/test/cases/serializers/xml_serialization_test.rb b/activemodel/test/cases/serializers/xml_serialization_test.rb
new file mode 100644
index 0000000000..5db14c8157
--- /dev/null
+++ b/activemodel/test/cases/serializers/xml_serialization_test.rb
@@ -0,0 +1,262 @@
+require 'cases/helper'
+require 'models/contact'
+require 'active_support/core_ext/object/instance_variables'
+require 'ostruct'
+
+class Contact
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :address, :friends, :contact
+
+ remove_method :attributes if method_defined?(:attributes)
+
+ def attributes
+ instance_values.except("address", "friends", "contact")
+ end
+end
+
+module Admin
+ class Contact < ::Contact
+ end
+end
+
+class Customer < Struct.new(:name)
+end
+
+class Address
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :street, :city, :state, :zip, :apt_number
+
+ def attributes
+ instance_values
+ end
+end
+
+class SerializableContact < Contact
+ def serializable_hash(options={})
+ super(options.merge(only: [:name, :age]))
+ end
+end
+
+class XmlSerializationTest < ActiveModel::TestCase
+ def setup
+ @contact = Contact.new
+ @contact.name = 'aaron stack'
+ @contact.age = 25
+ @contact.created_at = Time.utc(2006, 8, 1)
+ @contact.awesome = false
+ customer = Customer.new
+ customer.name = "John"
+ @contact.preferences = customer
+ @contact.address = Address.new
+ @contact.address.city = "Springfield"
+ @contact.address.apt_number = 35
+ @contact.friends = [Contact.new, Contact.new]
+ @contact.contact = SerializableContact.new
+ end
+
+ test "should serialize default root" do
+ xml = @contact.to_xml
+ assert_match %r{^<contact>}, xml
+ assert_match %r{</contact>$}, xml
+ end
+
+ test "should serialize namespaced root" do
+ xml = Admin::Contact.new(@contact.attributes).to_xml
+ assert_match %r{^<contact>}, xml
+ assert_match %r{</contact>$}, xml
+ end
+
+ test "should serialize default root with namespace" do
+ xml = @contact.to_xml namespace: "http://xml.rubyonrails.org/contact"
+ assert_match %r{^<contact xmlns="http://xml.rubyonrails.org/contact">}, xml
+ assert_match %r{</contact>$}, xml
+ end
+
+ test "should serialize custom root" do
+ xml = @contact.to_xml root: 'xml_contact'
+ assert_match %r{^<xml-contact>}, xml
+ assert_match %r{</xml-contact>$}, xml
+ end
+
+ test "should allow undasherized tags" do
+ xml = @contact.to_xml root: 'xml_contact', dasherize: false
+ assert_match %r{^<xml_contact>}, xml
+ assert_match %r{</xml_contact>$}, xml
+ assert_match %r{<created_at}, xml
+ end
+
+ test "should allow camelized tags" do
+ xml = @contact.to_xml root: 'xml_contact', camelize: true
+ assert_match %r{^<XmlContact>}, xml
+ assert_match %r{</XmlContact>$}, xml
+ assert_match %r{<CreatedAt}, xml
+ end
+
+ test "should allow lower-camelized tags" do
+ xml = @contact.to_xml root: 'xml_contact', camelize: :lower
+ assert_match %r{^<xmlContact>}, xml
+ assert_match %r{</xmlContact>$}, xml
+ assert_match %r{<createdAt}, xml
+ end
+
+ test "should use serializable hash" do
+ @contact = SerializableContact.new
+ @contact.name = 'aaron stack'
+ @contact.age = 25
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_match %r{<age type="integer">25</age>}, xml
+ assert_no_match %r{<awesome>}, xml
+ end
+
+ test "should allow skipped types" do
+ xml = @contact.to_xml skip_types: true
+ assert_match %r{<age>25</age>}, xml
+ end
+
+ test "should include yielded additions" do
+ xml_output = @contact.to_xml do |xml|
+ xml.creator "David"
+ end
+ assert_match %r{<creator>David</creator>}, xml_output
+ end
+
+ test "should serialize string" do
+ assert_match %r{<name>aaron stack</name>}, @contact.to_xml
+ end
+
+ test "should serialize nil" do
+ assert_match %r{<pseudonyms nil="true"/>}, @contact.to_xml(methods: :pseudonyms)
+ end
+
+ test "should serialize integer" do
+ assert_match %r{<age type="integer">25</age>}, @contact.to_xml
+ end
+
+ test "should serialize datetime" do
+ assert_match %r{<created-at type="dateTime">2006-08-01T00:00:00Z</created-at>}, @contact.to_xml
+ end
+
+ test "should serialize boolean" do
+ assert_match %r{<awesome type="boolean">false</awesome>}, @contact.to_xml
+ end
+
+ test "should serialize array" do
+ assert_match %r{<social type="array">\s*<social>twitter</social>\s*<social>github</social>\s*</social>}, @contact.to_xml(methods: :social)
+ end
+
+ test "should serialize hash" do
+ assert_match %r{<network>\s*<git type="symbol">github</git>\s*</network>}, @contact.to_xml(methods: :network)
+ end
+
+ test "should serialize yaml" do
+ assert_match %r{<preferences type="yaml">--- !ruby/struct:Customer(\s*)\nname: John\n</preferences>}, @contact.to_xml
+ end
+
+ test "should call proc on object" do
+ proc = Proc.new { |options| options[:builder].tag!('nationality', 'unknown') }
+ xml = @contact.to_xml(procs: [ proc ])
+ assert_match %r{<nationality>unknown</nationality>}, xml
+ end
+
+ test "should supply serializable to second proc argument" do
+ proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
+ xml = @contact.to_xml(procs: [ proc ])
+ assert_match %r{<name-reverse>kcats noraa</name-reverse>}, xml
+ end
+
+ test "should serialize string correctly when type passed" do
+ xml = @contact.to_xml type: 'Contact'
+ assert_match %r{<contact type="Contact">}, xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ end
+
+ test "include option with singular association" do
+ xml = @contact.to_xml include: :address, indent: 0
+ assert xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
+ end
+
+ test "include option with plural association" do
+ xml = @contact.to_xml include: :friends, indent: 0
+ assert_match %r{<friends type="array">}, xml
+ assert_match %r{<friend type="Contact">}, xml
+ end
+
+ class FriendList
+ def initialize(friends)
+ @friends = friends
+ end
+
+ def to_ary
+ @friends
+ end
+ end
+
+ test "include option with ary" do
+ @contact.friends = FriendList.new(@contact.friends)
+ xml = @contact.to_xml include: :friends, indent: 0
+ assert_match %r{<friends type="array">}, xml
+ assert_match %r{<friend type="Contact">}, xml
+ end
+
+ test "multiple includes" do
+ xml = @contact.to_xml indent: 0, skip_instruct: true, include: [ :address, :friends ]
+ assert xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
+ assert_match %r{<friends type="array">}, xml
+ assert_match %r{<friend type="Contact">}, xml
+ end
+
+ test "include with options" do
+ xml = @contact.to_xml indent: 0, skip_instruct: true, include: { address: { only: :city } }
+ assert xml.include?(%(><address><city>Springfield</city></address>))
+ end
+
+ test "propagates skip_types option to included associations" do
+ xml = @contact.to_xml include: :friends, indent: 0, skip_types: true
+ assert_match %r{<friends>}, xml
+ assert_match %r{<friend>}, xml
+ end
+
+ test "propagates skip-types option to included associations and attributes" do
+ xml = @contact.to_xml skip_types: true, include: :address, indent: 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number>}, xml
+ end
+
+ test "propagates camelize option to included associations and attributes" do
+ xml = @contact.to_xml camelize: true, include: :address, indent: 0
+ assert_match %r{<Address>}, xml
+ assert_match %r{<AptNumber type="integer">}, xml
+ end
+
+ test "propagates dasherize option to included associations and attributes" do
+ xml = @contact.to_xml dasherize: false, include: :address, indent: 0
+ assert_match %r{<apt_number type="integer">}, xml
+ end
+
+ test "don't propagate skip_types if skip_types is defined at the included association level" do
+ xml = @contact.to_xml skip_types: true, include: { address: { skip_types: false } }, indent: 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "don't propagate camelize if camelize is defined at the included association level" do
+ xml = @contact.to_xml camelize: true, include: { address: { camelize: false } }, indent: 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "don't propagate dasherize if dasherize is defined at the included association level" do
+ xml = @contact.to_xml dasherize: false, include: { address: { dasherize: true } }, indent: 0
+ assert_match %r{<address>}, xml
+ assert_match %r{<apt-number type="integer">}, xml
+ end
+
+ test "association with sti" do
+ xml = @contact.to_xml(include: :contact)
+ assert xml.include?(%(<contact type="SerializableContact">))
+ end
+end
diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb
new file mode 100644
index 0000000000..cedc812ec7
--- /dev/null
+++ b/activemodel/test/cases/translation_test.rb
@@ -0,0 +1,108 @@
+require 'cases/helper'
+require 'models/person'
+
+class ActiveModelI18nTests < ActiveModel::TestCase
+
+ def setup
+ I18n.backend = I18n::Backend::Simple.new
+ end
+
+ def teardown
+ I18n.backend.reload!
+ end
+
+ def test_translated_model_attributes
+ I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute' } } }
+ assert_equal 'person name attribute', Person.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_with_default
+ I18n.backend.store_translations 'en', attributes: { name: 'name default attribute' }
+ assert_equal 'name default attribute', Person.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_using_default_option
+ assert_equal 'name default attribute', Person.human_attribute_name('name', default: "name default attribute")
+ end
+
+ def test_translated_model_attributes_using_default_option_as_symbol
+ I18n.backend.store_translations 'en', default_name: 'name default attribute'
+ assert_equal 'name default attribute', Person.human_attribute_name('name', default: :default_name)
+ end
+
+ def test_translated_model_attributes_falling_back_to_default
+ assert_equal 'Name', Person.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_using_default_option_as_symbol_and_falling_back_to_default
+ assert_equal 'Name', Person.human_attribute_name('name', default: :default_name)
+ end
+
+ def test_translated_model_attributes_with_symbols
+ I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute'} } }
+ assert_equal 'person name attribute', Person.human_attribute_name(:name)
+ end
+
+ def test_translated_model_attributes_with_ancestor
+ I18n.backend.store_translations 'en', activemodel: { attributes: { child: { name: 'child name attribute'} } }
+ assert_equal 'child name attribute', Child.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_with_ancestors_fallback
+ I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute'} } }
+ assert_equal 'person name attribute', Child.human_attribute_name('name')
+ end
+
+ def test_translated_model_attributes_with_attribute_matching_namespaced_model_name
+ I18n.backend.store_translations 'en', activemodel: { attributes: {
+ person: { gender: 'person gender'},
+ :"person/gender" => { attribute: 'person gender attribute' }
+ } }
+
+ assert_equal 'person gender', Person.human_attribute_name('gender')
+ assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute')
+ end
+
+ def test_translated_deeply_nested_model_attributes
+ I18n.backend.store_translations 'en', activemodel: { attributes: { :"person/contacts/addresses" => { street: 'Deeply Nested Address Street' } } }
+ assert_equal 'Deeply Nested Address Street', Person.human_attribute_name('contacts.addresses.street')
+ end
+
+ def test_translated_nested_model_attributes
+ I18n.backend.store_translations 'en', activemodel: { attributes: { :"person/addresses" => { street: 'Person Address Street' } } }
+ assert_equal 'Person Address Street', Person.human_attribute_name('addresses.street')
+ end
+
+ def test_translated_nested_model_attributes_with_namespace_fallback
+ I18n.backend.store_translations 'en', activemodel: { attributes: { addresses: { street: 'Cool Address Street' } } }
+ assert_equal 'Cool Address Street', Person.human_attribute_name('addresses.street')
+ end
+
+ def test_translated_model_names
+ I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
+ assert_equal 'person model', Person.model_name.human
+ end
+
+ def test_translated_model_names_with_sti
+ I18n.backend.store_translations 'en', activemodel: { models: { child: 'child model' } }
+ assert_equal 'child model', Child.model_name.human
+ end
+
+ def test_translated_model_names_with_ancestors_fallback
+ I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
+ assert_equal 'person model', Child.model_name.human
+ end
+
+ def test_human_does_not_modify_options
+ options = { default: 'person model' }
+ Person.model_name.human(options)
+ assert_equal({ default: 'person model' }, options)
+ end
+
+ def test_human_attribute_name_does_not_modify_options
+ options = { default: 'Cool gender' }
+ Person.human_attribute_name('gender', options)
+ assert_equal({ default: 'Cool gender' }, options)
+ end
+end
+
diff --git a/activemodel/test/cases/validations/absence_validation_test.rb b/activemodel/test/cases/validations/absence_validation_test.rb
new file mode 100644
index 0000000000..ebfe1cf4e4
--- /dev/null
+++ b/activemodel/test/cases/validations/absence_validation_test.rb
@@ -0,0 +1,68 @@
+# encoding: utf-8
+require 'cases/helper'
+require 'models/topic'
+require 'models/person'
+require 'models/custom_reader'
+
+class AbsenceValidationTest < ActiveModel::TestCase
+ teardown do
+ Topic.clear_validators!
+ Person.clear_validators!
+ CustomReader.clear_validators!
+ end
+
+ def test_validates_absence_of
+ Topic.validates_absence_of(:title, :content)
+ t = Topic.new
+ t.title = "foo"
+ t.content = "bar"
+ assert t.invalid?
+ assert_equal ["must be blank"], t.errors[:title]
+ assert_equal ["must be blank"], t.errors[:content]
+ t.title = ""
+ t.content = "something"
+ assert t.invalid?
+ assert_equal ["must be blank"], t.errors[:content]
+ assert_equal [], t.errors[:title]
+ t.content = ""
+ assert t.valid?
+ end
+
+ def test_validates_absence_of_with_array_arguments
+ Topic.validates_absence_of %w(title content)
+ t = Topic.new
+ t.title = "foo"
+ t.content = "bar"
+ assert t.invalid?
+ assert_equal ["must be blank"], t.errors[:title]
+ assert_equal ["must be blank"], t.errors[:content]
+ end
+
+ def test_validates_absence_of_with_custom_error_using_quotes
+ Person.validates_absence_of :karma, message: "This string contains 'single' and \"double\" quotes"
+ p = Person.new
+ p.karma = "good"
+ assert p.invalid?
+ assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
+ end
+
+ def test_validates_absence_of_for_ruby_class
+ Person.validates_absence_of :karma
+ p = Person.new
+ p.karma = "good"
+ assert p.invalid?
+ assert_equal ["must be blank"], p.errors[:karma]
+ p.karma = nil
+ assert p.valid?
+ end
+
+ def test_validates_absence_of_for_ruby_class_with_custom_reader
+ CustomReader.validates_absence_of :karma
+ p = CustomReader.new
+ p[:karma] = "excellent"
+ assert p.invalid?
+ assert_equal ["must be blank"], p.errors[:karma]
+ p[:karma] = ""
+ assert p.valid?
+ end
+end
diff --git a/activemodel/test/cases/validations/acceptance_validation_test.rb b/activemodel/test/cases/validations/acceptance_validation_test.rb
new file mode 100644
index 0000000000..e78aa1adaf
--- /dev/null
+++ b/activemodel/test/cases/validations/acceptance_validation_test.rb
@@ -0,0 +1,68 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/reply'
+require 'models/person'
+
+class AcceptanceValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_terms_of_service_agreement_no_acceptance
+ Topic.validates_acceptance_of(:terms_of_service)
+
+ t = Topic.new("title" => "We should not be confirmed")
+ assert t.valid?
+ end
+
+ def test_terms_of_service_agreement
+ Topic.validates_acceptance_of(:terms_of_service)
+
+ t = Topic.new("title" => "We should be confirmed","terms_of_service" => "")
+ assert t.invalid?
+ assert_equal ["must be accepted"], t.errors[:terms_of_service]
+
+ t.terms_of_service = "1"
+ assert t.valid?
+ end
+
+ def test_eula
+ Topic.validates_acceptance_of(:eula, message: "must be abided")
+
+ t = Topic.new("title" => "We should be confirmed","eula" => "")
+ assert t.invalid?
+ assert_equal ["must be abided"], t.errors[:eula]
+
+ t.eula = "1"
+ assert t.valid?
+ end
+
+ def test_terms_of_service_agreement_with_accept_value
+ Topic.validates_acceptance_of(:terms_of_service, accept: "I agree.")
+
+ t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
+ assert t.invalid?
+ assert_equal ["must be accepted"], t.errors[:terms_of_service]
+
+ t.terms_of_service = "I agree."
+ assert t.valid?
+ end
+
+ def test_validates_acceptance_of_for_ruby_class
+ Person.validates_acceptance_of :karma
+
+ p = Person.new
+ p.karma = ""
+
+ assert p.invalid?
+ assert_equal ["must be accepted"], p.errors[:karma]
+
+ p.karma = "1"
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+end
diff --git a/activemodel/test/cases/validations/callbacks_test.rb b/activemodel/test/cases/validations/callbacks_test.rb
new file mode 100644
index 0000000000..6cd0f4ed4d
--- /dev/null
+++ b/activemodel/test/cases/validations/callbacks_test.rb
@@ -0,0 +1,98 @@
+# encoding: utf-8
+require 'cases/helper'
+
+class Dog
+ include ActiveModel::Validations
+ include ActiveModel::Validations::Callbacks
+
+ attr_accessor :name, :history
+
+ def initialize
+ @history = []
+ end
+end
+
+class DogWithMethodCallbacks < Dog
+ before_validation :set_before_validation_marker
+ after_validation :set_after_validation_marker
+
+ def set_before_validation_marker; self.history << 'before_validation_marker'; end
+ def set_after_validation_marker; self.history << 'after_validation_marker' ; end
+end
+
+class DogValidatorsAreProc < Dog
+ before_validation { self.history << 'before_validation_marker' }
+ after_validation { self.history << 'after_validation_marker' }
+end
+
+class DogWithTwoValidators < Dog
+ before_validation { self.history << 'before_validation_marker1' }
+ before_validation { self.history << 'before_validation_marker2' }
+end
+
+class DogValidatorReturningFalse < Dog
+ before_validation { false }
+ before_validation { self.history << 'before_validation_marker2' }
+end
+
+class DogWithMissingName < Dog
+ before_validation { self.history << 'before_validation_marker' }
+ validates_presence_of :name
+end
+
+class DogValidatorWithIfCondition < Dog
+ before_validation :set_before_validation_marker1, if: -> { true }
+ before_validation :set_before_validation_marker2, if: -> { false }
+
+ after_validation :set_after_validation_marker1, if: -> { true }
+ after_validation :set_after_validation_marker2, if: -> { false }
+
+ def set_before_validation_marker1; self.history << 'before_validation_marker1'; end
+ def set_before_validation_marker2; self.history << 'before_validation_marker2' ; end
+
+ def set_after_validation_marker1; self.history << 'after_validation_marker1'; end
+ def set_after_validation_marker2; self.history << 'after_validation_marker2' ; end
+end
+
+
+class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase
+
+ def test_if_condition_is_respected_for_before_validation
+ d = DogValidatorWithIfCondition.new
+ d.valid?
+ assert_equal ["before_validation_marker1", "after_validation_marker1"], d.history
+ end
+
+ def test_before_validation_and_after_validation_callbacks_should_be_called
+ d = DogWithMethodCallbacks.new
+ d.valid?
+ assert_equal ['before_validation_marker', 'after_validation_marker'], d.history
+ end
+
+ def test_before_validation_and_after_validation_callbacks_should_be_called_with_proc
+ d = DogValidatorsAreProc.new
+ d.valid?
+ assert_equal ['before_validation_marker', 'after_validation_marker'], d.history
+ end
+
+ def test_before_validation_and_after_validation_callbacks_should_be_called_in_declared_order
+ d = DogWithTwoValidators.new
+ d.valid?
+ assert_equal ['before_validation_marker1', 'before_validation_marker2'], d.history
+ end
+
+ def test_further_callbacks_should_not_be_called_if_before_validation_returns_false
+ d = DogValidatorReturningFalse.new
+ output = d.valid?
+ assert_equal [], d.history
+ assert_equal false, output
+ end
+
+ def test_validation_test_should_be_done
+ d = DogWithMissingName.new
+ output = d.valid?
+ assert_equal ['before_validation_marker'], d.history
+ assert_equal false, output
+ end
+
+end
diff --git a/activemodel/test/cases/validations/conditional_validation_test.rb b/activemodel/test/cases/validations/conditional_validation_test.rb
new file mode 100644
index 0000000000..1261937b56
--- /dev/null
+++ b/activemodel/test/cases/validations/conditional_validation_test.rb
@@ -0,0 +1,139 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+
+class ConditionalValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_if_validation_using_method_true
+ # When the method returns true
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true)
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_unless_validation_using_method_true
+ # When the method returns true
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: :condition_is_true)
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert_empty t.errors[:title]
+ end
+
+ def test_if_validation_using_method_false
+ # When the method returns false
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true_but_its_not)
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert_empty t.errors[:title]
+ end
+
+ def test_unless_validation_using_method_false
+ # When the method returns false
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: :condition_is_true_but_its_not)
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_if_validation_using_string_true
+ # When the evaluated string returns true
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: "a = 1; a == 1")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_unless_validation_using_string_true
+ # When the evaluated string returns true
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: "a = 1; a == 1")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert_empty t.errors[:title]
+ end
+
+ def test_if_validation_using_string_false
+ # When the evaluated string returns false
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: "false")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert_empty t.errors[:title]
+ end
+
+ def test_unless_validation_using_string_false
+ # When the evaluated string returns false
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: "false")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_if_validation_using_block_true
+ # When the block returns true
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
+ if: Proc.new { |r| r.content.size > 4 })
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_unless_validation_using_block_true
+ # When the block returns true
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
+ unless: Proc.new { |r| r.content.size > 4 })
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert_empty t.errors[:title]
+ end
+
+ def test_if_validation_using_block_false
+ # When the block returns false
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
+ if: Proc.new { |r| r.title != "uhohuhoh"})
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.valid?
+ assert_empty t.errors[:title]
+ end
+
+ def test_unless_validation_using_block_false
+ # When the block returns false
+ Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
+ unless: Proc.new { |r| r.title != "uhohuhoh"} )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ # previous implementation of validates_presence_of eval'd the
+ # string with the wrong binding, this regression test is to
+ # ensure that it works correctly
+ def test_validation_with_if_as_string
+ Topic.validates_presence_of(:title)
+ Topic.validates_presence_of(:author_name, if: "title.to_s.match('important')")
+
+ t = Topic.new
+ assert t.invalid?, "A topic without a title should not be valid"
+ assert_empty t.errors[:author_name], "A topic without an 'important' title should not require an author"
+
+ t.title = "Just a title"
+ assert t.valid?, "A topic with a basic title should be valid"
+
+ t.title = "A very important title"
+ assert t.invalid?, "A topic with an important title, but without an author, should not be valid"
+ assert t.errors[:author_name].any?, "A topic with an 'important' title should require an author"
+
+ t.author_name = "Hubert J. Farnsworth"
+ assert t.valid?, "A topic with an important title and author should be valid"
+ end
+end
diff --git a/activemodel/test/cases/validations/confirmation_validation_test.rb b/activemodel/test/cases/validations/confirmation_validation_test.rb
new file mode 100644
index 0000000000..65a2a1eb49
--- /dev/null
+++ b/activemodel/test/cases/validations/confirmation_validation_test.rb
@@ -0,0 +1,108 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class ConfirmationValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_no_title_confirmation
+ Topic.validates_confirmation_of(:title)
+
+ t = Topic.new(author_name: "Plutarch")
+ assert t.valid?
+
+ t.title_confirmation = "Parallel Lives"
+ assert t.invalid?
+
+ t.title_confirmation = nil
+ t.title = "Parallel Lives"
+ assert t.valid?
+
+ t.title_confirmation = "Parallel Lives"
+ assert t.valid?
+ end
+
+ def test_title_confirmation
+ Topic.validates_confirmation_of(:title)
+
+ t = Topic.new("title" => "We should be confirmed","title_confirmation" => "")
+ assert t.invalid?
+
+ t.title_confirmation = "We should be confirmed"
+ assert t.valid?
+ end
+
+ def test_validates_confirmation_of_for_ruby_class
+ Person.validates_confirmation_of :karma
+
+ p = Person.new
+ p.karma_confirmation = "None"
+ assert p.invalid?
+
+ assert_equal ["doesn't match Karma"], p.errors[:karma_confirmation]
+
+ p.karma = "None"
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+
+ def test_title_confirmation_with_i18n_attribute
+ begin
+ @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
+ I18n.load_path.clear
+ I18n.backend = I18n::Backend::Simple.new
+ I18n.backend.store_translations('en', {
+ errors: { messages: { confirmation: "doesn't match %{attribute}" } },
+ activemodel: { attributes: { topic: { title: 'Test Title'} } }
+ })
+
+ Topic.validates_confirmation_of(:title)
+
+ t = Topic.new("title" => "We should be confirmed","title_confirmation" => "")
+ assert t.invalid?
+ assert_equal ["doesn't match Test Title"], t.errors[:title_confirmation]
+ ensure
+ I18n.load_path.replace @old_load_path
+ I18n.backend = @old_backend
+ I18n.backend.reload!
+ end
+ end
+
+ test "does not override confirmation reader if present" do
+ klass = Class.new do
+ include ActiveModel::Validations
+
+ def title_confirmation
+ "expected title"
+ end
+
+ validates_confirmation_of :title
+ end
+
+ assert_equal "expected title", klass.new.title_confirmation,
+ "confirmation validation should not override the reader"
+ end
+
+ test "does not override confirmation writer if present" do
+ klass = Class.new do
+ include ActiveModel::Validations
+
+ def title_confirmation=(value)
+ @title_confirmation = "expected title"
+ end
+
+ validates_confirmation_of :title
+ end
+
+ model = klass.new
+ model.title_confirmation = "new title"
+ assert_equal "expected title", model.title_confirmation,
+ "confirmation validation should not override the writer"
+ end
+end
diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb
new file mode 100644
index 0000000000..1ce41f9bc9
--- /dev/null
+++ b/activemodel/test/cases/validations/exclusion_validation_test.rb
@@ -0,0 +1,92 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class ExclusionValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_validates_exclusion_of
+ Topic.validates_exclusion_of(:title, in: %w( abe monkey ))
+
+ assert Topic.new("title" => "something", "content" => "abc").valid?
+ assert Topic.new("title" => "monkey", "content" => "abc").invalid?
+ end
+
+ def test_validates_exclusion_of_with_formatted_message
+ Topic.validates_exclusion_of(:title, in: %w( abe monkey ), message: "option %{value} is restricted")
+
+ assert Topic.new("title" => "something", "content" => "abc")
+
+ t = Topic.new("title" => "monkey")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["option monkey is restricted"], t.errors[:title]
+ end
+
+ def test_validates_exclusion_of_with_within_option
+ Topic.validates_exclusion_of(:title, within: %w( abe monkey ))
+
+ assert Topic.new("title" => "something", "content" => "abc")
+
+ t = Topic.new("title" => "monkey")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ end
+
+ def test_validates_exclusion_of_for_ruby_class
+ Person.validates_exclusion_of :karma, in: %w( abe monkey )
+
+ p = Person.new
+ p.karma = "abe"
+ assert p.invalid?
+
+ assert_equal ["is reserved"], p.errors[:karma]
+
+ p.karma = "Lifo"
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+
+ def test_validates_exclusion_of_with_lambda
+ Topic.validates_exclusion_of :title, in: lambda { |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
+
+ t = Topic.new
+ t.title = "elephant"
+ t.author_name = "sikachu"
+ assert t.invalid?
+
+ t.title = "wasabi"
+ assert t.valid?
+ end
+
+ def test_validates_inclusion_of_with_symbol
+ Person.validates_exclusion_of :karma, in: :reserved_karmas
+
+ p = Person.new
+ p.karma = "abe"
+
+ def p.reserved_karmas
+ %w(abe)
+ end
+
+ assert p.invalid?
+ assert_equal ["is reserved"], p.errors[:karma]
+
+ p = Person.new
+ p.karma = "abe"
+
+ def p.reserved_karmas
+ %w()
+ end
+
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+end
diff --git a/activemodel/test/cases/validations/format_validation_test.rb b/activemodel/test/cases/validations/format_validation_test.rb
new file mode 100644
index 0000000000..0f91b73cd7
--- /dev/null
+++ b/activemodel/test/cases/validations/format_validation_test.rb
@@ -0,0 +1,149 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class PresenceValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_validate_format
+ Topic.validates_format_of(:title, :content, with: /\AValidation\smacros \w+!\z/, message: "is bad data")
+
+ t = Topic.new("title" => "i'm incorrect", "content" => "Validation macros rule!")
+ assert t.invalid?, "Shouldn't be valid"
+ assert_equal ["is bad data"], t.errors[:title]
+ assert t.errors[:content].empty?
+
+ t.title = "Validation macros rule!"
+
+ assert t.valid?
+ assert t.errors[:title].empty?
+
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, :content) }
+ end
+
+ def test_validate_format_with_allow_blank
+ Topic.validates_format_of(:title, with: /\AValidation\smacros \w+!\z/, allow_blank: true)
+ assert Topic.new("title" => "Shouldn't be valid").invalid?
+ assert Topic.new("title" => "").valid?
+ assert Topic.new("title" => nil).valid?
+ assert Topic.new("title" => "Validation macros rule!").valid?
+ end
+
+ # testing ticket #3142
+ def test_validate_format_numeric
+ Topic.validates_format_of(:title, :content, with: /\A[1-9][0-9]*\z/, message: "is bad data")
+
+ t = Topic.new("title" => "72x", "content" => "6789")
+ assert t.invalid?, "Shouldn't be valid"
+
+ assert_equal ["is bad data"], t.errors[:title]
+ assert t.errors[:content].empty?
+
+ t.title = "-11"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "03"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "z44"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "5v7"
+ assert t.invalid?, "Shouldn't be valid"
+
+ t.title = "1"
+
+ assert t.valid?
+ assert t.errors[:title].empty?
+ end
+
+ def test_validate_format_with_formatted_message
+ Topic.validates_format_of(:title, with: /\AValid Title\z/, message: "can't be %{value}")
+ t = Topic.new(title: 'Invalid title')
+ assert t.invalid?
+ assert_equal ["can't be Invalid title"], t.errors[:title]
+ end
+
+ def test_validate_format_of_with_multiline_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: /^Valid Title$/) }
+ end
+
+ def test_validate_format_of_with_multiline_regexp_and_option
+ assert_nothing_raised(ArgumentError) do
+ Topic.validates_format_of(:title, with: /^Valid Title$/, multiline: true)
+ end
+ end
+
+ def test_validate_format_with_not_option
+ Topic.validates_format_of(:title, without: /foo/, message: "should not contain foo")
+ t = Topic.new
+
+ t.title = "foobar"
+ t.valid?
+ assert_equal ["should not contain foo"], t.errors[:title]
+
+ t.title = "something else"
+ t.valid?
+ assert_equal [], t.errors[:title]
+ end
+
+ def test_validate_format_of_without_any_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title) }
+ end
+
+ def test_validates_format_of_with_both_regexps_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: /this/, without: /that/) }
+ end
+
+ def test_validates_format_of_when_with_isnt_a_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: "clearly not a regexp") }
+ end
+
+ def test_validates_format_of_when_not_isnt_a_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, without: "clearly not a regexp") }
+ end
+
+ def test_validates_format_of_with_lambda
+ Topic.validates_format_of :content, with: lambda { |topic| topic.title == "digit" ? /\A\d+\Z/ : /\A\S+\Z/ }
+
+ t = Topic.new
+ t.title = "digit"
+ t.content = "Pixies"
+ assert t.invalid?
+
+ t.content = "1234"
+ assert t.valid?
+ end
+
+ def test_validates_format_of_without_lambda
+ Topic.validates_format_of :content, without: lambda { |topic| topic.title == "characters" ? /\A\d+\Z/ : /\A\S+\Z/ }
+
+ t = Topic.new
+ t.title = "characters"
+ t.content = "1234"
+ assert t.invalid?
+
+ t.content = "Pixies"
+ assert t.valid?
+ end
+
+ def test_validates_format_of_for_ruby_class
+ Person.validates_format_of :karma, with: /\A\d+\Z/
+
+ p = Person.new
+ p.karma = "Pixies"
+ assert p.invalid?
+
+ assert_equal ["is invalid"], p.errors[:karma]
+
+ p.karma = "1234"
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+end
diff --git a/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
new file mode 100644
index 0000000000..3eeb80a48b
--- /dev/null
+++ b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
@@ -0,0 +1,150 @@
+require "cases/helper"
+
+require 'models/person'
+
+class I18nGenerateMessageValidationTest < ActiveModel::TestCase
+ def setup
+ Person.clear_validators!
+ @person = Person.new
+ end
+
+ # validates_inclusion_of: generate_message(attr_name, :inclusion, message: custom_message, value: value)
+ def test_generate_message_inclusion_with_default_message
+ assert_equal 'is not included in the list', @person.errors.generate_message(:title, :inclusion, value: 'title')
+ end
+
+ def test_generate_message_inclusion_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :inclusion, message: 'custom message %{value}', value: 'title')
+ end
+
+ # validates_exclusion_of: generate_message(attr_name, :exclusion, message: custom_message, value: value)
+ def test_generate_message_exclusion_with_default_message
+ assert_equal 'is reserved', @person.errors.generate_message(:title, :exclusion, value: 'title')
+ end
+
+ def test_generate_message_exclusion_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :exclusion, message: 'custom message %{value}', value: 'title')
+ end
+
+ # validates_format_of: generate_message(attr_name, :invalid, message: custom_message, value: value)
+ def test_generate_message_invalid_with_default_message
+ assert_equal 'is invalid', @person.errors.generate_message(:title, :invalid, value: 'title')
+ end
+
+ def test_generate_message_invalid_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :invalid, message: 'custom message %{value}', value: 'title')
+ end
+
+ # validates_confirmation_of: generate_message(attr_name, :confirmation, message: custom_message)
+ def test_generate_message_confirmation_with_default_message
+ assert_equal "doesn't match Title", @person.errors.generate_message(:title, :confirmation)
+ end
+
+ def test_generate_message_confirmation_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :confirmation, message: 'custom message')
+ end
+
+ # validates_acceptance_of: generate_message(attr_name, :accepted, message: custom_message)
+ def test_generate_message_accepted_with_default_message
+ assert_equal "must be accepted", @person.errors.generate_message(:title, :accepted)
+ end
+
+ def test_generate_message_accepted_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :accepted, message: 'custom message')
+ end
+
+ # add_on_empty: generate_message(attr, :empty, message: custom_message)
+ def test_generate_message_empty_with_default_message
+ assert_equal "can't be empty", @person.errors.generate_message(:title, :empty)
+ end
+
+ def test_generate_message_empty_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :empty, message: 'custom message')
+ end
+
+ # add_on_blank: generate_message(attr, :blank, message: custom_message)
+ def test_generate_message_blank_with_default_message
+ assert_equal "can't be blank", @person.errors.generate_message(:title, :blank)
+ end
+
+ def test_generate_message_blank_with_custom_message
+ assert_equal 'custom message', @person.errors.generate_message(:title, :blank, message: 'custom message')
+ end
+
+ # validates_length_of: generate_message(attr, :too_long, message: custom_message, count: option_value.end)
+ def test_generate_message_too_long_with_default_message_plural
+ assert_equal "is too long (maximum is 10 characters)", @person.errors.generate_message(:title, :too_long, count: 10)
+ end
+
+ def test_generate_message_too_long_with_default_message_singular
+ assert_equal "is too long (maximum is 1 character)", @person.errors.generate_message(:title, :too_long, count: 1)
+ end
+
+ def test_generate_message_too_long_with_custom_message
+ assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_long, message: 'custom message %{count}', count: 10)
+ end
+
+ # validates_length_of: generate_message(attr, :too_short, default: custom_message, count: option_value.begin)
+ def test_generate_message_too_short_with_default_message_plural
+ assert_equal "is too short (minimum is 10 characters)", @person.errors.generate_message(:title, :too_short, count: 10)
+ end
+
+ def test_generate_message_too_short_with_default_message_singular
+ assert_equal "is too short (minimum is 1 character)", @person.errors.generate_message(:title, :too_short, count: 1)
+ end
+
+ def test_generate_message_too_short_with_custom_message
+ assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_short, message: 'custom message %{count}', count: 10)
+ end
+
+ # validates_length_of: generate_message(attr, :wrong_length, message: custom_message, count: option_value)
+ def test_generate_message_wrong_length_with_default_message_plural
+ assert_equal "is the wrong length (should be 10 characters)", @person.errors.generate_message(:title, :wrong_length, count: 10)
+ end
+
+ def test_generate_message_wrong_length_with_default_message_singular
+ assert_equal "is the wrong length (should be 1 character)", @person.errors.generate_message(:title, :wrong_length, count: 1)
+ end
+
+ def test_generate_message_wrong_length_with_custom_message
+ assert_equal 'custom message 10', @person.errors.generate_message(:title, :wrong_length, message: 'custom message %{count}', count: 10)
+ end
+
+ # validates_numericality_of: generate_message(attr_name, :not_a_number, value: raw_value, message: custom_message)
+ def test_generate_message_not_a_number_with_default_message
+ assert_equal "is not a number", @person.errors.generate_message(:title, :not_a_number, value: 'title')
+ end
+
+ def test_generate_message_not_a_number_with_custom_message
+ assert_equal 'custom message title', @person.errors.generate_message(:title, :not_a_number, message: 'custom message %{value}', value: 'title')
+ end
+
+ # validates_numericality_of: generate_message(attr_name, option, value: raw_value, default: custom_message)
+ def test_generate_message_greater_than_with_default_message
+ assert_equal "must be greater than 10", @person.errors.generate_message(:title, :greater_than, value: 'title', count: 10)
+ end
+
+ def test_generate_message_greater_than_or_equal_to_with_default_message
+ assert_equal "must be greater than or equal to 10", @person.errors.generate_message(:title, :greater_than_or_equal_to, value: 'title', count: 10)
+ end
+
+ def test_generate_message_equal_to_with_default_message
+ assert_equal "must be equal to 10", @person.errors.generate_message(:title, :equal_to, value: 'title', count: 10)
+ end
+
+ def test_generate_message_less_than_with_default_message
+ assert_equal "must be less than 10", @person.errors.generate_message(:title, :less_than, value: 'title', count: 10)
+ end
+
+ def test_generate_message_less_than_or_equal_to_with_default_message
+ assert_equal "must be less than or equal to 10", @person.errors.generate_message(:title, :less_than_or_equal_to, value: 'title', count: 10)
+ end
+
+ def test_generate_message_odd_with_default_message
+ assert_equal "must be odd", @person.errors.generate_message(:title, :odd, value: 'title', count: 10)
+ end
+
+ def test_generate_message_even_with_default_message
+ assert_equal "must be even", @person.errors.generate_message(:title, :even, value: 'title', count: 10)
+ end
+end
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
new file mode 100644
index 0000000000..96084a32ba
--- /dev/null
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -0,0 +1,373 @@
+# -*- coding: utf-8 -*-
+
+require "cases/helper"
+require 'models/person'
+
+class I18nValidationTest < ActiveModel::TestCase
+
+ def setup
+ Person.clear_validators!
+ @person = Person.new
+
+ @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
+ I18n.load_path.clear
+ I18n.backend = I18n::Backend::Simple.new
+ I18n.backend.store_translations('en', errors: { messages: { custom: nil } })
+ end
+
+ def teardown
+ Person.clear_validators!
+ I18n.load_path.replace @old_load_path
+ I18n.backend = @old_backend
+ I18n.backend.reload!
+ end
+
+ def test_full_message_encoding
+ I18n.backend.store_translations('en', errors: {
+ messages: { too_short: '猫舌' } })
+ Person.validates_length_of :title, within: 3..5
+ @person.valid?
+ assert_equal ['Title 猫舌'], @person.errors.full_messages
+ end
+
+ def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
+ @person.errors.add(:name, 'not found')
+ Person.expects(:human_attribute_name).with(:name, default: 'Name').returns("Person's name")
+ assert_equal ["Person's name not found"], @person.errors.full_messages
+ end
+
+ def test_errors_full_messages_uses_format
+ I18n.backend.store_translations('en', errors: { format: "Field %{attribute} %{message}" })
+ @person.errors.add('name', 'empty')
+ assert_equal ["Field Name empty"], @person.errors.full_messages
+ end
+
+ # ActiveModel::Validations
+
+ # A set of common cases for ActiveModel::Validations message generation that
+ # are used to generate tests to keep things DRY
+ #
+ COMMON_CASES = [
+ # [ case, validation_options, generate_message_options]
+ [ "given no options", {}, {}],
+ [ "given custom message", { message: "custom" }, { message: "custom" }],
+ [ "given if condition", { if: lambda { true }}, {}],
+ [ "given unless condition", { unless: lambda { false }}, {}],
+ [ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }]
+ ]
+
+ # validates_confirmation_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_confirmation_of on generated message #{name}" do
+ Person.validates_confirmation_of :title, validation_options
+ @person.title_confirmation = 'foo'
+ @person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title'))
+ @person.valid?
+ end
+ end
+
+ # validates_acceptance_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_acceptance_of on generated message #{name}" do
+ Person.validates_acceptance_of :title, validation_options.merge(allow_nil: false)
+ @person.errors.expects(:generate_message).with(:title, :accepted, generate_message_options)
+ @person.valid?
+ end
+ end
+
+ # validates_presence_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_presence_of on generated message #{name}" do
+ Person.validates_presence_of :title, validation_options
+ @person.errors.expects(:generate_message).with(:title, :blank, generate_message_options)
+ @person.valid?
+ end
+ end
+
+ # validates_length_of :within too short w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_length_of for :withing on generated message when too short #{name}" do
+ Person.validates_length_of :title, validation_options.merge(within: 3..5)
+ @person.errors.expects(:generate_message).with(:title, :too_short, generate_message_options.merge(count: 3))
+ @person.valid?
+ end
+ end
+
+ # validates_length_of :within too long w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_length_of for :too_long generated message #{name}" do
+ Person.validates_length_of :title, validation_options.merge(within: 3..5)
+ @person.title = 'this title is too long'
+ @person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(count: 5))
+ @person.valid?
+ end
+ end
+
+ # validates_length_of :is w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_length_of for :is on generated message #{name}" do
+ Person.validates_length_of :title, validation_options.merge(is: 5)
+ @person.errors.expects(:generate_message).with(:title, :wrong_length, generate_message_options.merge(count: 5))
+ @person.valid?
+ end
+ end
+
+ # validates_format_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_format_of on generated message #{name}" do
+ Person.validates_format_of :title, validation_options.merge(with: /\A[1-9][0-9]*\z/)
+ @person.title = '72x'
+ @person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(value: '72x'))
+ @person.valid?
+ end
+ end
+
+ # validates_inclusion_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_inclusion_of on generated message #{name}" do
+ Person.validates_inclusion_of :title, validation_options.merge(in: %w(a b c))
+ @person.title = 'z'
+ @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
+ @person.valid?
+ end
+ end
+
+ # validates_inclusion_of using :within w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_inclusion_of using :within on generated message #{name}" do
+ Person.validates_inclusion_of :title, validation_options.merge(within: %w(a b c))
+ @person.title = 'z'
+ @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
+ @person.valid?
+ end
+ end
+
+ # validates_exclusion_of w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_exclusion_of generated message #{name}" do
+ Person.validates_exclusion_of :title, validation_options.merge(in: %w(a b c))
+ @person.title = 'a'
+ @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
+ @person.valid?
+ end
+ end
+
+ # validates_exclusion_of using :within w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_exclusion_of using :within generated message #{name}" do
+ Person.validates_exclusion_of :title, validation_options.merge(within: %w(a b c))
+ @person.title = 'a'
+ @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of without :only_integer w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options
+ @person.title = 'a'
+ @person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(value: 'a'))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of with :only_integer w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of for :only_integer on generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options.merge(only_integer: true)
+ @person.title = '0.0'
+ @person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(value: '0.0'))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of :odd w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of for :odd on generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options.merge(only_integer: true, odd: true)
+ @person.title = 0
+ @person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(value: 0))
+ @person.valid?
+ end
+ end
+
+ # validates_numericality_of :less_than w/ mocha
+
+ COMMON_CASES.each do |name, validation_options, generate_message_options|
+ test "validates_numericality_of for :less_than on generated message #{name}" do
+ Person.validates_numericality_of :title, validation_options.merge(only_integer: true, less_than: 0)
+ @person.title = 1
+ @person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(value: 1, count: 0))
+ @person.valid?
+ end
+ end
+
+
+ # To make things DRY this macro is defined to define 3 tests for every validation case.
+ def self.set_expectations_for_validation(validation, error_type, &block_that_sets_validation)
+ if error_type == :confirmation
+ attribute = :title_confirmation
+ else
+ attribute = :title
+ end
+ # test "validates_confirmation_of finds custom model key translation when blank"
+ test "#{validation} finds custom model key translation when #{error_type}" do
+ I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message' } } } } } }
+ I18n.backend.store_translations 'en', errors: { messages: { error_type => 'global message'}}
+
+ yield(@person, {})
+ @person.valid?
+ assert_equal ['custom message'], @person.errors[attribute]
+ end
+
+ # test "validates_confirmation_of finds custom model key translation with interpolation when blank"
+ test "#{validation} finds custom model key translation with interpolation when #{error_type}" do
+ I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message with %{extra}' } } } } } }
+ I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
+
+ yield(@person, { extra: "extra information" })
+ @person.valid?
+ assert_equal ['custom message with extra information'], @person.errors[attribute]
+ end
+
+ # test "validates_confirmation_of finds global default key translation when blank"
+ test "#{validation} finds global default key translation when #{error_type}" do
+ I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
+
+ yield(@person, {})
+ @person.valid?
+ assert_equal ['global message'], @person.errors[attribute]
+ end
+ end
+
+ # validates_confirmation_of w/o mocha
+
+ set_expectations_for_validation "validates_confirmation_of", :confirmation do |person, options_to_merge|
+ Person.validates_confirmation_of :title, options_to_merge
+ person.title_confirmation = 'foo'
+ end
+
+ # validates_acceptance_of w/o mocha
+
+ set_expectations_for_validation "validates_acceptance_of", :accepted do |person, options_to_merge|
+ Person.validates_acceptance_of :title, options_to_merge.merge(allow_nil: false)
+ end
+
+ # validates_presence_of w/o mocha
+
+ set_expectations_for_validation "validates_presence_of", :blank do |person, options_to_merge|
+ Person.validates_presence_of :title, options_to_merge
+ end
+
+ # validates_length_of :within w/o mocha
+
+ set_expectations_for_validation "validates_length_of", :too_short do |person, options_to_merge|
+ Person.validates_length_of :title, options_to_merge.merge(within: 3..5)
+ end
+
+ set_expectations_for_validation "validates_length_of", :too_long do |person, options_to_merge|
+ Person.validates_length_of :title, options_to_merge.merge(within: 3..5)
+ person.title = "too long"
+ end
+
+ # validates_length_of :is w/o mocha
+
+ set_expectations_for_validation "validates_length_of", :wrong_length do |person, options_to_merge|
+ Person.validates_length_of :title, options_to_merge.merge(is: 5)
+ end
+
+ # validates_format_of w/o mocha
+
+ set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge|
+ Person.validates_format_of :title, options_to_merge.merge(with: /\A[1-9][0-9]*\z/)
+ end
+
+ # validates_inclusion_of w/o mocha
+
+ set_expectations_for_validation "validates_inclusion_of", :inclusion do |person, options_to_merge|
+ Person.validates_inclusion_of :title, options_to_merge.merge(in: %w(a b c))
+ end
+
+ # validates_exclusion_of w/o mocha
+
+ set_expectations_for_validation "validates_exclusion_of", :exclusion do |person, options_to_merge|
+ Person.validates_exclusion_of :title, options_to_merge.merge(in: %w(a b c))
+ person.title = 'a'
+ end
+
+ # validates_numericality_of without :only_integer w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :not_a_number do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge
+ person.title = 'a'
+ end
+
+ # validates_numericality_of with :only_integer w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :not_an_integer do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true)
+ person.title = '1.0'
+ end
+
+ # validates_numericality_of :odd w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :odd do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, odd: true)
+ person.title = 0
+ end
+
+ # validates_numericality_of :less_than w/o mocha
+
+ set_expectations_for_validation "validates_numericality_of", :less_than do |person, options_to_merge|
+ Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, less_than: 0)
+ person.title = 1
+ end
+
+ # test with validates_with
+
+ def test_validations_with_message_symbol_must_translate
+ I18n.backend.store_translations 'en', errors: { messages: { custom_error: "I am a custom error" } }
+ Person.validates_presence_of :title, message: :custom_error
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+
+ def test_validates_with_message_symbol_must_translate_per_attribute
+ I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { title: { custom_error: "I am a custom error" } } } } } }
+ Person.validates_presence_of :title, message: :custom_error
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+
+ def test_validates_with_message_symbol_must_translate_per_model
+ I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { custom_error: "I am a custom error" } } } }
+ Person.validates_presence_of :title, message: :custom_error
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+
+ def test_validates_with_message_string
+ Person.validates_presence_of :title, message: "I am a custom error"
+ @person.title = nil
+ @person.valid?
+ assert_equal ["I am a custom error"], @person.errors[:title]
+ end
+end
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
new file mode 100644
index 0000000000..3a8f3080e1
--- /dev/null
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -0,0 +1,147 @@
+# encoding: utf-8
+require 'cases/helper'
+require 'active_support/all'
+
+require 'models/topic'
+require 'models/person'
+
+class InclusionValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_validates_inclusion_of_range
+ Topic.validates_inclusion_of(:title, in: 'aaa'..'bbb')
+ assert Topic.new("title" => "bbc", "content" => "abc").invalid?
+ assert Topic.new("title" => "aa", "content" => "abc").invalid?
+ assert Topic.new("title" => "aaab", "content" => "abc").invalid?
+ assert Topic.new("title" => "aaa", "content" => "abc").valid?
+ assert Topic.new("title" => "abc", "content" => "abc").valid?
+ assert Topic.new("title" => "bbb", "content" => "abc").valid?
+ end
+
+ def test_validates_inclusion_of_time_range
+ Topic.validates_inclusion_of(:created_at, in: 1.year.ago..Time.now)
+ assert Topic.new(title: 'aaa', created_at: 2.years.ago).invalid?
+ assert Topic.new(title: 'aaa', created_at: 3.months.ago).valid?
+ assert Topic.new(title: 'aaa', created_at: 37.weeks.from_now).invalid?
+ end
+
+ def test_validates_inclusion_of_date_range
+ Topic.validates_inclusion_of(:created_at, in: 1.year.until(Date.today)..Date.today)
+ assert Topic.new(title: 'aaa', created_at: 2.years.until(Date.today)).invalid?
+ assert Topic.new(title: 'aaa', created_at: 3.months.until(Date.today)).valid?
+ assert Topic.new(title: 'aaa', created_at: 37.weeks.since(Date.today)).invalid?
+ end
+
+ def test_validates_inclusion_of_date_time_range
+ Topic.validates_inclusion_of(:created_at, in: 1.year.until(DateTime.current)..DateTime.current)
+ assert Topic.new(title: 'aaa', created_at: 2.years.until(DateTime.current)).invalid?
+ assert Topic.new(title: 'aaa', created_at: 3.months.until(DateTime.current)).valid?
+ assert Topic.new(title: 'aaa', created_at: 37.weeks.since(DateTime.current)).invalid?
+ end
+
+ def test_validates_inclusion_of
+ Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ))
+
+ assert Topic.new("title" => "a!", "content" => "abc").invalid?
+ assert Topic.new("title" => "a b", "content" => "abc").invalid?
+ assert Topic.new("title" => nil, "content" => "def").invalid?
+
+ t = Topic.new("title" => "a", "content" => "I know you are but what am I?")
+ assert t.valid?
+ t.title = "uhoh"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is not included in the list"], t.errors[:title]
+
+ assert_raise(ArgumentError) { Topic.validates_inclusion_of(:title, in: nil) }
+ assert_raise(ArgumentError) { Topic.validates_inclusion_of(:title, in: 0) }
+
+ assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: "hi!") }
+ assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: {}) }
+ assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: []) }
+ end
+
+ def test_validates_inclusion_of_with_allow_nil
+ Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ), allow_nil: true)
+
+ assert Topic.new("title" => "a!", "content" => "abc").invalid?
+ assert Topic.new("title" => "", "content" => "abc").invalid?
+ assert Topic.new("title" => nil, "content" => "abc").valid?
+ end
+
+ def test_validates_inclusion_of_with_formatted_message
+ Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ), message: "option %{value} is not in the list")
+
+ assert Topic.new("title" => "a", "content" => "abc").valid?
+
+ t = Topic.new("title" => "uhoh", "content" => "abc")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["option uhoh is not in the list"], t.errors[:title]
+ end
+
+ def test_validates_inclusion_of_with_within_option
+ Topic.validates_inclusion_of(:title, within: %w( a b c d e f g ))
+
+ assert Topic.new("title" => "a", "content" => "abc").valid?
+
+ t = Topic.new("title" => "uhoh", "content" => "abc")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ end
+
+ def test_validates_inclusion_of_for_ruby_class
+ Person.validates_inclusion_of :karma, in: %w( abe monkey )
+
+ p = Person.new
+ p.karma = "Lifo"
+ assert p.invalid?
+
+ assert_equal ["is not included in the list"], p.errors[:karma]
+
+ p.karma = "monkey"
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+
+ def test_validates_inclusion_of_with_lambda
+ Topic.validates_inclusion_of :title, in: lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
+
+ t = Topic.new
+ t.title = "wasabi"
+ t.author_name = "sikachu"
+ assert t.invalid?
+
+ t.title = "elephant"
+ assert t.valid?
+ end
+
+ def test_validates_inclusion_of_with_symbol
+ Person.validates_inclusion_of :karma, in: :available_karmas
+
+ p = Person.new
+ p.karma = "Lifo"
+
+ def p.available_karmas
+ %w()
+ end
+
+ assert p.invalid?
+ assert_equal ["is not included in the list"], p.errors[:karma]
+
+ p = Person.new
+ p.karma = "Lifo"
+
+ def p.available_karmas
+ %w(Lifo)
+ end
+
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+end
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
new file mode 100644
index 0000000000..046ffcb16f
--- /dev/null
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -0,0 +1,424 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+class LengthValidationTest < ActiveModel::TestCase
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_validates_length_of_with_allow_nil
+ Topic.validates_length_of( :title, is: 5, allow_nil: true )
+
+ assert Topic.new("title" => "ab").invalid?
+ assert Topic.new("title" => "").invalid?
+ assert Topic.new("title" => nil).valid?
+ assert Topic.new("title" => "abcde").valid?
+ end
+
+ def test_validates_length_of_with_allow_blank
+ Topic.validates_length_of( :title, is: 5, allow_blank: true )
+
+ assert Topic.new("title" => "ab").invalid?
+ assert Topic.new("title" => "").valid?
+ assert Topic.new("title" => nil).valid?
+ assert Topic.new("title" => "abcde").valid?
+ end
+
+ def test_validates_length_of_using_minimum
+ Topic.validates_length_of :title, minimum: 5
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "not"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors[:title]
+
+ t.title = ""
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors[:title]
+
+ t.title = nil
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_maximum_should_allow_nil
+ Topic.validates_length_of :title, maximum: 10
+ t = Topic.new
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_minimum
+ Topic.validates_length_of :title, minimum: 5, allow_nil: true
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_maximum
+ Topic.validates_length_of :title, maximum: 5
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "notvalid"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors[:title]
+
+ t.title = ""
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_maximum
+ Topic.validates_length_of :title, maximum: 5, allow_nil: true
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_within
+ Topic.validates_length_of(:title, :content, within: 3..5)
+
+ t = Topic.new("title" => "a!", "content" => "I'm ooooooooh so very long")
+ assert t.invalid?
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content]
+
+ t.title = nil
+ t.content = nil
+ assert t.invalid?
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:content]
+
+ t.title = "abe"
+ t.content = "mad"
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_within_with_exclusive_range
+ Topic.validates_length_of(:title, within: 4...10)
+
+ t = Topic.new("title" => "9 chars!!")
+ assert t.valid?
+
+ t.title = "Now I'm 10"
+ assert t.invalid?
+ assert_equal ["is too long (maximum is 9 characters)"], t.errors[:title]
+
+ t.title = "Four"
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_within
+ Topic.validates_length_of :title, :content, within: 3..5, allow_nil: true
+
+ t = Topic.new('title' => 'abc', 'content' => 'abcd')
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_is
+ Topic.validates_length_of :title, is: 5
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "notvalid"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is the wrong length (should be 5 characters)"], t.errors[:title]
+
+ t.title = ""
+ assert t.invalid?
+
+ t.title = nil
+ assert t.invalid?
+ end
+
+ def test_optionally_validates_length_of_using_is
+ Topic.validates_length_of :title, is: 5, allow_nil: true
+
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.valid?
+
+ t.title = nil
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_bignum
+ bigmin = 2 ** 30
+ bigmax = 2 ** 32
+ bigrange = bigmin...bigmax
+ assert_nothing_raised do
+ Topic.validates_length_of :title, is: bigmin + 5
+ Topic.validates_length_of :title, within: bigrange
+ Topic.validates_length_of :title, in: bigrange
+ Topic.validates_length_of :title, minimum: bigmin
+ Topic.validates_length_of :title, maximum: bigmax
+ end
+ end
+
+ def test_validates_length_of_nasty_params
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, is: -6) }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, within: 6) }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, minimum: "a") }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, maximum: "a") }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, within: "a") }
+ assert_raise(ArgumentError) { Topic.validates_length_of(:title, is: "a") }
+ end
+
+ def test_validates_length_of_custom_errors_for_minimum_with_message
+ Topic.validates_length_of( :title, minimum: 5, message: "boo %{count}" )
+ t = Topic.new("title" => "uhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["boo 5"], t.errors[:title]
+ end
+
+ def test_validates_length_of_custom_errors_for_minimum_with_too_short
+ Topic.validates_length_of( :title, minimum: 5, too_short: "hoo %{count}" )
+ t = Topic.new("title" => "uhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors[:title]
+ end
+
+ def test_validates_length_of_custom_errors_for_maximum_with_message
+ Topic.validates_length_of( :title, maximum: 5, message: "boo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["boo 5"], t.errors[:title]
+ end
+
+ def test_validates_length_of_custom_errors_for_in
+ Topic.validates_length_of(:title, in: 10..20, message: "hoo %{count}")
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 10"], t.errors["title"]
+
+ t = Topic.new("title" => "uhohuhohuhohuhohuhohuhohuhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 20"], t.errors["title"]
+ end
+
+ def test_validates_length_of_custom_errors_for_maximum_with_too_long
+ Topic.validates_length_of( :title, maximum: 5, too_long: "hoo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_validates_length_of_custom_errors_for_both_too_short_and_too_long
+ Topic.validates_length_of :title, minimum: 3, maximum: 5, too_short: 'too short', too_long: 'too long'
+
+ t = Topic.new(title: 'a')
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ['too short'], t.errors['title']
+
+ t = Topic.new(title: 'aaaaaa')
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ['too long'], t.errors['title']
+ end
+
+ def test_validates_length_of_custom_errors_for_is_with_message
+ Topic.validates_length_of( :title, is: 5, message: "boo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["boo 5"], t.errors["title"]
+ end
+
+ def test_validates_length_of_custom_errors_for_is_with_wrong_length
+ Topic.validates_length_of( :title, is: 5, wrong_length: "hoo %{count}" )
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["hoo 5"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_minimum_utf8
+ Topic.validates_length_of :title, minimum: 5
+
+ t = Topic.new("title" => "一二三四五", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "一二三四"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_maximum_utf8
+ Topic.validates_length_of :title, maximum: 5
+
+ t = Topic.new("title" => "一二三四五", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "一二34五六"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_using_within_utf8
+ Topic.validates_length_of(:title, :content, within: 3..5)
+
+ t = Topic.new("title" => "一二", "content" => "12三四五六七")
+ assert t.invalid?
+ assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title]
+ assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content]
+ t.title = "一二三"
+ t.content = "12三"
+ assert t.valid?
+ end
+
+ def test_optionally_validates_length_of_using_within_utf8
+ Topic.validates_length_of :title, within: 3..5, allow_nil: true
+
+ t = Topic.new(title: "一二三四五")
+ assert t.valid?, t.errors.inspect
+
+ t = Topic.new(title: "一二三")
+ assert t.valid?, t.errors.inspect
+
+ t.title = nil
+ assert t.valid?, t.errors.inspect
+ end
+
+ def test_validates_length_of_using_is_utf8
+ Topic.validates_length_of :title, is: 5
+
+ t = Topic.new("title" => "一二345", "content" => "whatever")
+ assert t.valid?
+
+ t.title = "一二345六"
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["is the wrong length (should be 5 characters)"], t.errors["title"]
+ end
+
+ def test_validates_length_of_with_block
+ Topic.validates_length_of :content, minimum: 5, too_short: "Your essay must be at least %{count} words.",
+ tokenizer: lambda {|str| str.scan(/\w+/) }
+ t = Topic.new(content: "this content should be long enough")
+ assert t.valid?
+
+ t.content = "not long enough"
+ assert t.invalid?
+ assert t.errors[:content].any?
+ assert_equal ["Your essay must be at least 5 words."], t.errors[:content]
+ end
+
+ def test_validates_length_of_for_fixnum
+ Topic.validates_length_of(:approved, is: 4)
+
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever", approved: 1)
+ assert t.invalid?
+ assert t.errors[:approved].any?
+
+ t = Topic.new("title" => "uhohuhoh", "content" => "whatever", approved: 1234)
+ assert t.valid?
+ end
+
+ def test_validates_length_of_for_ruby_class
+ Person.validates_length_of :karma, minimum: 5
+
+ p = Person.new
+ p.karma = "Pix"
+ assert p.invalid?
+
+ assert_equal ["is too short (minimum is 5 characters)"], p.errors[:karma]
+
+ p.karma = "The Smiths"
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+
+ def test_validates_length_of_for_infinite_maxima
+ Topic.validates_length_of(:title, within: 5..Float::INFINITY)
+
+ t = Topic.new("title" => "1234")
+ assert t.invalid?
+ assert t.errors[:title].any?
+
+ t.title = "12345"
+ assert t.valid?
+
+ Topic.validates_length_of(:author_name, maximum: Float::INFINITY)
+
+ assert t.valid?
+
+ t.author_name = "A very long author name that should still be valid." * 100
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_maximum_should_not_allow_nil_when_nil_not_allowed
+ Topic.validates_length_of :title, maximum: 10, allow_nil: false
+ t = Topic.new
+ assert t.invalid?
+ end
+
+ def test_validates_length_of_using_maximum_should_not_allow_nil_and_empty_string_when_blank_not_allowed
+ Topic.validates_length_of :title, maximum: 10, allow_blank: false
+ t = Topic.new
+ assert t.invalid?
+
+ t.title = ""
+ assert t.invalid?
+ end
+
+ def test_validates_length_of_using_both_minimum_and_maximum_should_not_allow_nil
+ Topic.validates_length_of :title, minimum: 5, maximum: 10
+ t = Topic.new
+ assert t.invalid?
+ end
+
+ def test_validates_length_of_using_minimum_0_should_not_allow_nil
+ Topic.validates_length_of :title, minimum: 0
+ t = Topic.new
+ assert t.invalid?
+
+ t.title = ""
+ assert t.valid?
+ end
+
+ def test_validates_length_of_using_is_0_should_not_allow_nil
+ Topic.validates_length_of :title, is: 0
+ t = Topic.new
+ assert t.invalid?
+
+ t.title = ""
+ assert t.valid?
+ end
+
+ def test_validates_with_diff_in_option
+ Topic.validates_length_of(:title, is: 5)
+ Topic.validates_length_of(:title, is: 5, if: Proc.new { false } )
+
+ assert Topic.new("title" => "david").valid?
+ assert Topic.new("title" => "david2").invalid?
+ end
+end
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
new file mode 100644
index 0000000000..3834d327ea
--- /dev/null
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -0,0 +1,211 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+
+require 'bigdecimal'
+
+class NumericalityValidationTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ NIL = [nil]
+ BLANK = ["", " ", " \t \r \n"]
+ BIGDECIMAL_STRINGS = %w(12345678901234567890.1234567890) # 30 significant digits
+ FLOAT_STRINGS = %w(0.0 +0.0 -0.0 10.0 10.5 -10.5 -0.0001 -090.1 90.1e1 -90.1e5 -90.1e-5 90e-5)
+ INTEGER_STRINGS = %w(0 +0 -0 10 +10 -10 0090 -090)
+ FLOATS = [0.0, 10.0, 10.5, -10.5, -0.0001] + FLOAT_STRINGS
+ INTEGERS = [0, 10, -10] + INTEGER_STRINGS
+ BIGDECIMAL = BIGDECIMAL_STRINGS.collect! { |bd| BigDecimal.new(bd) }
+ JUNK = ["not a number", "42 not a number", "0xdeadbeef", "0xinvalidhex", "0Xdeadbeef", "00-1", "--3", "+-3", "+3-1", "-+019.0", "12.12.13.12", "123\nnot a number"]
+ INFINITY = [1.0/0.0]
+
+ def test_default_validates_numericality_of
+ Topic.validates_numericality_of :approved
+ invalid!(NIL + BLANK + JUNK)
+ valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
+ end
+
+ def test_validates_numericality_of_with_nil_allowed
+ Topic.validates_numericality_of :approved, allow_nil: true
+
+ invalid!(JUNK + BLANK)
+ valid!(NIL + FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
+ end
+
+ def test_validates_numericality_of_with_integer_only
+ Topic.validates_numericality_of :approved, only_integer: true
+
+ invalid!(NIL + BLANK + JUNK + FLOATS + BIGDECIMAL + INFINITY)
+ valid!(INTEGERS)
+ end
+
+ def test_validates_numericality_of_with_integer_only_and_nil_allowed
+ Topic.validates_numericality_of :approved, only_integer: true, allow_nil: true
+
+ invalid!(JUNK + BLANK + FLOATS + BIGDECIMAL + INFINITY)
+ valid!(NIL + INTEGERS)
+ end
+
+ def test_validates_numericality_of_with_integer_only_and_symbol_as_value
+ Topic.validates_numericality_of :approved, only_integer: :condition_is_true_but_its_not
+
+ invalid!(NIL + BLANK + JUNK)
+ valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
+ end
+
+ def test_validates_numericality_of_with_integer_only_and_proc_as_value
+ Topic.send(:define_method, :allow_only_integers?, lambda { false })
+ Topic.validates_numericality_of :approved, only_integer: Proc.new {|topic| topic.allow_only_integers? }
+
+ invalid!(NIL + BLANK + JUNK)
+ valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
+ end
+
+ def test_validates_numericality_with_greater_than
+ Topic.validates_numericality_of :approved, greater_than: 10
+
+ invalid!([-10, 10], 'must be greater than 10')
+ valid!([11])
+ end
+
+ def test_validates_numericality_with_greater_than_or_equal
+ Topic.validates_numericality_of :approved, greater_than_or_equal_to: 10
+
+ invalid!([-9, 9], 'must be greater than or equal to 10')
+ valid!([10])
+ end
+
+ def test_validates_numericality_with_equal_to
+ Topic.validates_numericality_of :approved, equal_to: 10
+
+ invalid!([-10, 11] + INFINITY, 'must be equal to 10')
+ valid!([10])
+ end
+
+ def test_validates_numericality_with_less_than
+ Topic.validates_numericality_of :approved, less_than: 10
+
+ invalid!([10], 'must be less than 10')
+ valid!([-9, 9])
+ end
+
+ def test_validates_numericality_with_less_than_or_equal_to
+ Topic.validates_numericality_of :approved, less_than_or_equal_to: 10
+
+ invalid!([11], 'must be less than or equal to 10')
+ valid!([-10, 10])
+ end
+
+ def test_validates_numericality_with_odd
+ Topic.validates_numericality_of :approved, odd: true
+
+ invalid!([-2, 2], 'must be odd')
+ valid!([-1, 1])
+ end
+
+ def test_validates_numericality_with_even
+ Topic.validates_numericality_of :approved, even: true
+
+ invalid!([-1, 1], 'must be even')
+ valid!([-2, 2])
+ end
+
+ def test_validates_numericality_with_greater_than_less_than_and_even
+ Topic.validates_numericality_of :approved, greater_than: 1, less_than: 4, even: true
+
+ invalid!([1, 3, 4])
+ valid!([2])
+ end
+
+ def test_validates_numericality_with_other_than
+ Topic.validates_numericality_of :approved, other_than: 0
+
+ invalid!([0, 0.0])
+ valid!([-1, 42])
+ end
+
+ def test_validates_numericality_with_proc
+ Topic.send(:define_method, :min_approved, lambda { 5 })
+ Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new {|topic| topic.min_approved }
+
+ invalid!([3, 4])
+ valid!([5, 6])
+ ensure
+ Topic.send(:remove_method, :min_approved)
+ end
+
+ def test_validates_numericality_with_symbol
+ Topic.send(:define_method, :max_approved, lambda { 5 })
+ Topic.validates_numericality_of :approved, less_than_or_equal_to: :max_approved
+
+ invalid!([6])
+ valid!([4, 5])
+ ensure
+ Topic.send(:remove_method, :max_approved)
+ end
+
+ def test_validates_numericality_with_numeric_message
+ Topic.validates_numericality_of :approved, less_than: 4, message: "smaller than %{count}"
+ topic = Topic.new("title" => "numeric test", "approved" => 10)
+
+ assert !topic.valid?
+ assert_equal ["smaller than 4"], topic.errors[:approved]
+
+ Topic.validates_numericality_of :approved, greater_than: 4, message: "greater than %{count}"
+ topic = Topic.new("title" => "numeric test", "approved" => 1)
+
+ assert !topic.valid?
+ assert_equal ["greater than 4"], topic.errors[:approved]
+ end
+
+ def test_validates_numericality_of_for_ruby_class
+ Person.validates_numericality_of :karma, allow_nil: false
+
+ p = Person.new
+ p.karma = "Pix"
+ assert p.invalid?
+
+ assert_equal ["is not a number"], p.errors[:karma]
+
+ p.karma = "1234"
+ assert p.valid?
+ ensure
+ Person.clear_validators!
+ end
+
+ def test_validates_numericality_with_invalid_args
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than_or_equal_to: "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than_or_equal_to: "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than: "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than: "foo" }
+ assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, equal_to: "foo" }
+ end
+
+ private
+
+ def invalid!(values, error = nil)
+ with_each_topic_approved_value(values) do |topic, value|
+ assert topic.invalid?, "#{value.inspect} not rejected as a number"
+ assert topic.errors[:approved].any?, "FAILED for #{value.inspect}"
+ assert_equal error, topic.errors[:approved].first if error
+ end
+ end
+
+ def valid!(values)
+ with_each_topic_approved_value(values) do |topic, value|
+ assert topic.valid?, "#{value.inspect} not accepted as a number"
+ end
+ end
+
+ def with_each_topic_approved_value(values)
+ topic = Topic.new(title: "numeric test", content: "whatever")
+ values.each do |value|
+ topic.approved = value
+ yield topic, value
+ end
+ end
+end
diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb
new file mode 100644
index 0000000000..ecf16d1e16
--- /dev/null
+++ b/activemodel/test/cases/validations/presence_validation_test.rb
@@ -0,0 +1,107 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/person'
+require 'models/custom_reader'
+
+class PresenceValidationTest < ActiveModel::TestCase
+
+ teardown do
+ Topic.clear_validators!
+ Person.clear_validators!
+ CustomReader.clear_validators!
+ end
+
+ def test_validate_presences
+ Topic.validates_presence_of(:title, :content)
+
+ t = Topic.new
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+ assert_equal ["can't be blank"], t.errors[:content]
+
+ t.title = "something"
+ t.content = " "
+
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:content]
+
+ t.content = "like stuff"
+
+ assert t.valid?
+ end
+
+ def test_accepts_array_arguments
+ Topic.validates_presence_of %w(title content)
+ t = Topic.new
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+ assert_equal ["can't be blank"], t.errors[:content]
+ end
+
+ def test_validates_acceptance_of_with_custom_error_using_quotes
+ Person.validates_presence_of :karma, message: "This string contains 'single' and \"double\" quotes"
+ p = Person.new
+ assert p.invalid?
+ assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
+ end
+
+ def test_validates_presence_of_for_ruby_class
+ Person.validates_presence_of :karma
+
+ p = Person.new
+ assert p.invalid?
+
+ assert_equal ["can't be blank"], p.errors[:karma]
+
+ p.karma = "Cold"
+ assert p.valid?
+ end
+
+ def test_validates_presence_of_for_ruby_class_with_custom_reader
+ CustomReader.validates_presence_of :karma
+
+ p = CustomReader.new
+ assert p.invalid?
+
+ assert_equal ["can't be blank"], p.errors[:karma]
+
+ p[:karma] = "Cold"
+ assert p.valid?
+ end
+
+ def test_validates_presence_of_with_allow_nil_option
+ Topic.validates_presence_of(:title, allow_nil: true)
+
+ t = Topic.new(title: "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = " "
+ assert t.invalid?, t.errors.full_messages
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
+
+ def test_validates_presence_of_with_allow_blank_option
+ Topic.validates_presence_of(:title, allow_blank: true)
+
+ t = Topic.new(title: "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.valid?, t.errors.full_messages
+
+ t.title = " "
+ assert t.valid?, t.errors.full_messages
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
+end
diff --git a/activemodel/test/cases/validations/validates_test.rb b/activemodel/test/cases/validations/validates_test.rb
new file mode 100644
index 0000000000..699a872e42
--- /dev/null
+++ b/activemodel/test/cases/validations/validates_test.rb
@@ -0,0 +1,159 @@
+# encoding: utf-8
+require 'cases/helper'
+require 'models/person'
+require 'models/topic'
+require 'models/person_with_validator'
+require 'validators/email_validator'
+require 'validators/namespace/email_validator'
+
+class ValidatesTest < ActiveModel::TestCase
+ setup :reset_callbacks
+ teardown :reset_callbacks
+
+ def reset_callbacks
+ Person.clear_validators!
+ Topic.clear_validators!
+ PersonWithValidator.clear_validators!
+ end
+
+ def test_validates_with_messages_empty
+ Person.validates :title, presence: { message: "" }
+ person = Person.new
+ assert !person.valid?, 'person should not be valid.'
+ end
+
+ def test_validates_with_built_in_validation
+ Person.validates :title, numericality: true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not a number'], person.errors[:title]
+ end
+
+ def test_validates_with_attribute_specified_as_string
+ Person.validates "title", numericality: true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not a number'], person.errors[:title]
+
+ person = Person.new
+ person.title = 123
+ assert person.valid?
+ end
+
+ def test_validates_with_built_in_validation_and_options
+ Person.validates :salary, numericality: { message: 'my custom message' }
+ person = Person.new
+ person.valid?
+ assert_equal ['my custom message'], person.errors[:salary]
+ end
+
+ def test_validates_with_validator_class
+ Person.validates :karma, email: true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not an email'], person.errors[:karma]
+ end
+
+ def test_validates_with_namespaced_validator_class
+ Person.validates :karma, :'namespace/email' => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not an email'], person.errors[:karma]
+ end
+
+ def test_validates_with_if_as_local_conditions
+ Person.validates :karma, presence: true, email: { unless: :condition_is_true }
+ person = Person.new
+ person.valid?
+ assert_equal ["can't be blank"], person.errors[:karma]
+ end
+
+ def test_validates_with_if_as_shared_conditions
+ Person.validates :karma, presence: true, email: true, if: :condition_is_true
+ person = Person.new
+ person.valid?
+ assert_equal ["can't be blank", "is not an email"], person.errors[:karma].sort
+ end
+
+ def test_validates_with_unless_shared_conditions
+ Person.validates :karma, presence: true, email: true, unless: :condition_is_true
+ person = Person.new
+ assert person.valid?
+ end
+
+ def test_validates_with_allow_nil_shared_conditions
+ Person.validates :karma, length: { minimum: 20 }, email: true, allow_nil: true
+ person = Person.new
+ assert person.valid?
+ end
+
+ def test_validates_with_regexp
+ Person.validates :karma, format: /positive|negative/
+ person = Person.new
+ assert person.invalid?
+ assert_equal ['is invalid'], person.errors[:karma]
+ person.karma = "positive"
+ assert person.valid?
+ end
+
+ def test_validates_with_array
+ Person.validates :gender, inclusion: %w(m f)
+ person = Person.new
+ assert person.invalid?
+ assert_equal ['is not included in the list'], person.errors[:gender]
+ person.gender = "m"
+ assert person.valid?
+ end
+
+ def test_validates_with_range
+ Person.validates :karma, length: 6..20
+ person = Person.new
+ assert person.invalid?
+ assert_equal ['is too short (minimum is 6 characters)'], person.errors[:karma]
+ person.karma = 'something'
+ assert person.valid?
+ end
+
+ def test_validates_with_validator_class_and_options
+ Person.validates :karma, email: { message: 'my custom message' }
+ person = Person.new
+ person.valid?
+ assert_equal ['my custom message'], person.errors[:karma]
+ end
+
+ def test_validates_with_unknown_validator
+ assert_raise(ArgumentError) { Person.validates :karma, unknown: true }
+ end
+
+ def test_validates_with_included_validator
+ PersonWithValidator.validates :title, presence: true
+ person = PersonWithValidator.new
+ person.valid?
+ assert_equal ['Local validator'], person.errors[:title]
+ end
+
+ def test_validates_with_included_validator_and_options
+ PersonWithValidator.validates :title, presence: { custom: ' please' }
+ person = PersonWithValidator.new
+ person.valid?
+ assert_equal ['Local validator please'], person.errors[:title]
+ end
+
+ def test_validates_with_included_validator_and_wildcard_shortcut
+ # Shortcut for PersonWithValidator.validates :title, like: { with: "Mr." }
+ PersonWithValidator.validates :title, like: "Mr."
+ person = PersonWithValidator.new
+ person.title = "Ms. Pacman"
+ person.valid?
+ assert_equal ['does not appear to be like Mr.'], person.errors[:title]
+ end
+
+ def test_defining_extra_default_keys_for_validates
+ Topic.validates :title, confirmation: true, message: 'Y U NO CONFIRM'
+ topic = Topic.new
+ topic.title = "What's happening"
+ topic.title_confirmation = "Not this"
+ assert !topic.valid?
+ assert_equal ['Y U NO CONFIRM'], topic.errors[:title_confirmation]
+ end
+end
diff --git a/activemodel/test/cases/validations/validations_context_test.rb b/activemodel/test/cases/validations/validations_context_test.rb
new file mode 100644
index 0000000000..005bf118c6
--- /dev/null
+++ b/activemodel/test/cases/validations/validations_context_test.rb
@@ -0,0 +1,50 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+
+class ValidationsContextTest < ActiveModel::TestCase
+ def teardown
+ Topic.clear_validators!
+ end
+
+ ERROR_MESSAGE = "Validation error from validator"
+
+ class ValidatorThatAddsErrors < ActiveModel::Validator
+ def validate(record)
+ record.errors[:base] << ERROR_MESSAGE
+ end
+ end
+
+ test "with a class that adds errors on create and validating a new model with no arguments" do
+ Topic.validates_with(ValidatorThatAddsErrors, on: :create)
+ topic = Topic.new
+ assert topic.valid?, "Validation doesn't run on valid? if 'on' is set to create"
+ end
+
+ test "with a class that adds errors on update and validating a new model" do
+ Topic.validates_with(ValidatorThatAddsErrors, on: :update)
+ topic = Topic.new
+ assert topic.valid?(:create), "Validation doesn't run on create if 'on' is set to update"
+ end
+
+ test "with a class that adds errors on create and validating a new model" do
+ Topic.validates_with(ValidatorThatAddsErrors, on: :create)
+ topic = Topic.new
+ assert topic.invalid?(:create), "Validation does run on create if 'on' is set to create"
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "with a class that adds errors on multiple contexts and validating a new model" do
+ Topic.validates_with(ValidatorThatAddsErrors, on: [:context1, :context2])
+
+ topic = Topic.new
+ assert topic.valid?, "Validation ran with no context given when 'on' is set to context1 and context2"
+
+ assert topic.invalid?(:context1), "Validation did not run on context1 when 'on' is set to context1 and context2"
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+
+ assert topic.invalid?(:context2), "Validation did not run on context2 when 'on' is set to context1 and context2"
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+end
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
new file mode 100644
index 0000000000..736c2deea8
--- /dev/null
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -0,0 +1,172 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+
+class ValidatesWithTest < ActiveModel::TestCase
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ ERROR_MESSAGE = "Validation error from validator"
+ OTHER_ERROR_MESSAGE = "Validation error from other validator"
+
+ class ValidatorThatAddsErrors < ActiveModel::Validator
+ def validate(record)
+ record.errors[:base] << ERROR_MESSAGE
+ end
+ end
+
+ class OtherValidatorThatAddsErrors < ActiveModel::Validator
+ def validate(record)
+ record.errors[:base] << OTHER_ERROR_MESSAGE
+ end
+ end
+
+ class ValidatorThatDoesNotAddErrors < ActiveModel::Validator
+ def validate(record)
+ end
+ end
+
+ class ValidatorThatValidatesOptions < ActiveModel::Validator
+ def validate(record)
+ if options[:field] == :first_name
+ record.errors[:base] << ERROR_MESSAGE
+ end
+ end
+ end
+
+ class ValidatorPerEachAttribute < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ record.errors[attribute] << "Value is #{value}"
+ end
+ end
+
+ class ValidatorCheckValidity < ActiveModel::EachValidator
+ def check_validity!
+ raise "boom!"
+ end
+ end
+
+ test "validation with class that adds errors" do
+ Topic.validates_with(ValidatorThatAddsErrors)
+ topic = Topic.new
+ assert topic.invalid?, "A class that adds errors causes the record to be invalid"
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "with a class that returns valid" do
+ Topic.validates_with(ValidatorThatDoesNotAddErrors)
+ topic = Topic.new
+ assert topic.valid?, "A class that does not add errors does not cause the record to be invalid"
+ end
+
+ test "with multiple classes" do
+ Topic.validates_with(ValidatorThatAddsErrors, OtherValidatorThatAddsErrors)
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ assert topic.errors[:base].include?(OTHER_ERROR_MESSAGE)
+ end
+
+ test "with if statements that return false" do
+ Topic.validates_with(ValidatorThatAddsErrors, if: "1 == 2")
+ topic = Topic.new
+ assert topic.valid?
+ end
+
+ test "with if statements that return true" do
+ Topic.validates_with(ValidatorThatAddsErrors, if: "1 == 1")
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "with unless statements that return true" do
+ Topic.validates_with(ValidatorThatAddsErrors, unless: "1 == 1")
+ topic = Topic.new
+ assert topic.valid?
+ end
+
+ test "with unless statements that returns false" do
+ Topic.validates_with(ValidatorThatAddsErrors, unless: "1 == 2")
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "passes all configuration options to the validator class" do
+ topic = Topic.new
+ validator = mock()
+ validator.expects(:new).with(foo: :bar, if: "1 == 1", class: Topic).returns(validator)
+ validator.expects(:validate).with(topic)
+
+ Topic.validates_with(validator, if: "1 == 1", foo: :bar)
+ assert topic.valid?
+ end
+
+ test "validates_with with options" do
+ Topic.validates_with(ValidatorThatValidatesOptions, field: :first_name)
+ topic = Topic.new
+ assert topic.invalid?
+ assert topic.errors[:base].include?(ERROR_MESSAGE)
+ end
+
+ test "validates_with each validator" do
+ Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content])
+ topic = Topic.new title: "Title", content: "Content"
+ assert topic.invalid?
+ assert_equal ["Value is Title"], topic.errors[:title]
+ assert_equal ["Value is Content"], topic.errors[:content]
+ end
+
+ test "each validator checks validity" do
+ assert_raise RuntimeError do
+ Topic.validates_with(ValidatorCheckValidity, attributes: [:title])
+ end
+ end
+
+ test "each validator expects attributes to be given" do
+ assert_raise ArgumentError do
+ Topic.validates_with(ValidatorPerEachAttribute)
+ end
+ end
+
+ test "each validator skip nil values if :allow_nil is set to true" do
+ Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_nil: true)
+ topic = Topic.new content: ""
+ assert topic.invalid?
+ assert topic.errors[:title].empty?
+ assert_equal ["Value is "], topic.errors[:content]
+ end
+
+ test "each validator skip blank values if :allow_blank is set to true" do
+ Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_blank: true)
+ topic = Topic.new content: ""
+ assert topic.valid?
+ assert topic.errors[:title].empty?
+ assert topic.errors[:content].empty?
+ end
+
+ test "validates_with can validate with an instance method" do
+ Topic.validates :title, with: :my_validation
+
+ topic = Topic.new title: "foo"
+ assert topic.valid?
+ assert topic.errors[:title].empty?
+
+ topic = Topic.new
+ assert !topic.valid?
+ assert_equal ['is missing'], topic.errors[:title]
+ end
+
+ test "optionally pass in the attribute being validated when validating with an instance method" do
+ Topic.validates :title, :content, with: :my_validation_with_arg
+
+ topic = Topic.new title: "foo"
+ assert !topic.valid?
+ assert topic.errors[:title].empty?
+ assert_equal ['is missing'], topic.errors[:content]
+ end
+end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
new file mode 100644
index 0000000000..ba0aacc2a5
--- /dev/null
+++ b/activemodel/test/cases/validations_test.rb
@@ -0,0 +1,392 @@
+# encoding: utf-8
+require 'cases/helper'
+
+require 'models/topic'
+require 'models/reply'
+require 'models/custom_reader'
+
+require 'active_support/json'
+require 'active_support/xml_mini'
+
+class ValidationsTest < ActiveModel::TestCase
+ class CustomStrictValidationException < StandardError; end
+
+ def teardown
+ Topic.clear_validators!
+ end
+
+ def test_single_field_validation
+ r = Reply.new
+ r.title = "There's no content!"
+ assert r.invalid?, "A reply without content shouldn't be savable"
+ assert r.after_validation_performed, "after_validation callback should be called"
+
+ r.content = "Messa content!"
+ assert r.valid?, "A reply with content should be savable"
+ assert r.after_validation_performed, "after_validation callback should be called"
+ end
+
+ def test_single_attr_validation_and_error_msg
+ r = Reply.new
+ r.title = "There's no content!"
+ assert r.invalid?
+ assert r.errors[:content].any?, "A reply without content should mark that attribute as invalid"
+ assert_equal ["is Empty"], r.errors["content"], "A reply without content should contain an error"
+ assert_equal 1, r.errors.count
+ end
+
+ def test_double_attr_validation_and_error_msg
+ r = Reply.new
+ assert r.invalid?
+
+ assert r.errors[:title].any?, "A reply without title should mark that attribute as invalid"
+ assert_equal ["is Empty"], r.errors["title"], "A reply without title should contain an error"
+
+ assert r.errors[:content].any?, "A reply without content should mark that attribute as invalid"
+ assert_equal ["is Empty"], r.errors["content"], "A reply without content should contain an error"
+
+ assert_equal 2, r.errors.count
+ end
+
+ def test_single_error_per_attr_iteration
+ r = Reply.new
+ r.valid?
+
+ errors = r.errors.collect {|attr, messages| [attr.to_s, messages]}
+
+ assert errors.include?(["title", "is Empty"])
+ assert errors.include?(["content", "is Empty"])
+ end
+
+ def test_multiple_errors_per_attr_iteration_with_full_error_composition
+ r = Reply.new
+ r.title = ""
+ r.content = ""
+ r.valid?
+
+ errors = r.errors.to_a
+
+ assert_equal "Content is Empty", errors[0]
+ assert_equal "Title is Empty", errors[1]
+ assert_equal 2, r.errors.count
+ end
+
+ def test_errors_on_nested_attributes_expands_name
+ t = Topic.new
+ t.errors["replies.name"] << "can't be blank"
+ assert_equal ["Replies name can't be blank"], t.errors.full_messages
+ end
+
+ def test_errors_on_base
+ r = Reply.new
+ r.content = "Mismatch"
+ r.valid?
+ r.errors.add(:base, "Reply is not dignifying")
+
+ errors = r.errors.to_a.inject([]) { |result, error| result + [error] }
+
+ assert_equal ["Reply is not dignifying"], r.errors[:base]
+
+ assert errors.include?("Title is Empty")
+ assert errors.include?("Reply is not dignifying")
+ assert_equal 2, r.errors.count
+ end
+
+ def test_errors_on_base_with_symbol_message
+ r = Reply.new
+ r.content = "Mismatch"
+ r.valid?
+ r.errors.add(:base, :invalid)
+
+ errors = r.errors.to_a.inject([]) { |result, error| result + [error] }
+
+ assert_equal ["is invalid"], r.errors[:base]
+
+ assert errors.include?("Title is Empty")
+ assert errors.include?("is invalid")
+
+ assert_equal 2, r.errors.count
+ end
+
+ def test_errors_empty_after_errors_on_check
+ t = Topic.new
+ assert t.errors[:id].empty?
+ assert t.errors.empty?
+ end
+
+ def test_validates_each
+ hits = 0
+ Topic.validates_each(:title, :content, [:title, :content]) do |record, attr|
+ record.errors.add attr, 'gotcha'
+ hits += 1
+ end
+ t = Topic.new("title" => "valid", "content" => "whatever")
+ assert t.invalid?
+ assert_equal 4, hits
+ assert_equal %w(gotcha gotcha), t.errors[:title]
+ assert_equal %w(gotcha gotcha), t.errors[:content]
+ end
+
+ def test_validates_each_custom_reader
+ hits = 0
+ CustomReader.validates_each(:title, :content, [:title, :content]) do |record, attr|
+ record.errors.add attr, 'gotcha'
+ hits += 1
+ end
+ t = CustomReader.new("title" => "valid", "content" => "whatever")
+ assert t.invalid?
+ assert_equal 4, hits
+ assert_equal %w(gotcha gotcha), t.errors[:title]
+ assert_equal %w(gotcha gotcha), t.errors[:content]
+ ensure
+ CustomReader.clear_validators!
+ end
+
+ def test_validate_block
+ Topic.validate { errors.add("title", "will never be valid") }
+ t = Topic.new("title" => "Title", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["will never be valid"], t.errors["title"]
+ end
+
+ def test_validate_block_with_params
+ Topic.validate { |topic| topic.errors.add("title", "will never be valid") }
+ t = Topic.new("title" => "Title", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["will never be valid"], t.errors["title"]
+ end
+
+ def test_invalid_validator
+ Topic.validate :i_dont_exist
+ assert_raises(NoMethodError) do
+ t = Topic.new
+ t.valid?
+ end
+ end
+
+ def test_invalid_options_to_validate
+ assert_raises(ArgumentError) do
+ # A common mistake -- we meant to call 'validates'
+ Topic.validate :title, presence: true
+ end
+ end
+
+ def test_errors_conversions
+ Topic.validates_presence_of %w(title content)
+ t = Topic.new
+ assert t.invalid?
+
+ xml = t.errors.to_xml
+ assert_match %r{<errors>}, xml
+ assert_match %r{<error>Title can't be blank</error>}, xml
+ assert_match %r{<error>Content can't be blank</error>}, xml
+
+ hash = {}
+ hash[:title] = ["can't be blank"]
+ hash[:content] = ["can't be blank"]
+ assert_equal t.errors.to_json, hash.to_json
+ end
+
+ def test_validation_order
+ Topic.validates_presence_of :title
+ Topic.validates_length_of :title, minimum: 2
+
+ t = Topic.new("title" => "")
+ assert t.invalid?
+ assert_equal "can't be blank", t.errors["title"].first
+ Topic.validates_presence_of :title, :author_name
+ Topic.validate {errors.add('author_email_address', 'will never be valid')}
+ Topic.validates_length_of :title, :content, minimum: 2
+
+ t = Topic.new title: ''
+ assert t.invalid?
+
+ assert_equal :title, key = t.errors.keys[0]
+ assert_equal "can't be blank", t.errors[key][0]
+ assert_equal 'is too short (minimum is 2 characters)', t.errors[key][1]
+ assert_equal :author_name, key = t.errors.keys[1]
+ assert_equal "can't be blank", t.errors[key][0]
+ assert_equal :author_email_address, key = t.errors.keys[2]
+ assert_equal 'will never be valid', t.errors[key][0]
+ assert_equal :content, key = t.errors.keys[3]
+ assert_equal 'is too short (minimum is 2 characters)', t.errors[key][0]
+ end
+
+ def test_validation_with_if_and_on
+ Topic.validates_presence_of :title, if: Proc.new{|x| x.author_name = "bad"; true }, on: :update
+
+ t = Topic.new(title: "")
+
+ # If block should not fire
+ assert t.valid?
+ assert t.author_name.nil?
+
+ # If block should fire
+ assert t.invalid?(:update)
+ assert t.author_name == "bad"
+ end
+
+ def test_invalid_should_be_the_opposite_of_valid
+ Topic.validates_presence_of :title
+
+ t = Topic.new
+ assert t.invalid?
+ assert t.errors[:title].any?
+
+ t.title = 'Things are going to change'
+ assert !t.invalid?
+ end
+
+ def test_validation_with_message_as_proc
+ Topic.validates_presence_of(:title, message: proc { "no blanks here".upcase })
+
+ t = Topic.new
+ assert t.invalid?
+ assert_equal ["NO BLANKS HERE"], t.errors[:title]
+ end
+
+ def test_list_of_validators_for_model
+ Topic.validates_presence_of :title
+ Topic.validates_length_of :title, minimum: 2
+
+ assert_equal 2, Topic.validators.count
+ assert_equal [:presence, :length], Topic.validators.map(&:kind)
+ end
+
+ def test_list_of_validators_on_an_attribute
+ Topic.validates_presence_of :title, :content
+ Topic.validates_length_of :title, minimum: 2
+
+ assert_equal 2, Topic.validators_on(:title).count
+ assert_equal [:presence, :length], Topic.validators_on(:title).map(&:kind)
+ assert_equal 1, Topic.validators_on(:content).count
+ assert_equal [:presence], Topic.validators_on(:content).map(&:kind)
+ end
+
+ def test_accessing_instance_of_validator_on_an_attribute
+ Topic.validates_length_of :title, minimum: 10
+ assert_equal 10, Topic.validators_on(:title).first.options[:minimum]
+ end
+
+ def test_list_of_validators_on_multiple_attributes
+ Topic.validates :title, length: { minimum: 10 }
+ Topic.validates :author_name, presence: true, format: /a/
+
+ validators = Topic.validators_on(:title, :author_name)
+
+ assert_equal [
+ ActiveModel::Validations::FormatValidator,
+ ActiveModel::Validations::LengthValidator,
+ ActiveModel::Validations::PresenceValidator
+ ], validators.map { |v| v.class }.sort_by { |c| c.to_s }
+ end
+
+ def test_list_of_validators_will_be_empty_when_empty
+ Topic.validates :title, length: { minimum: 10 }
+ assert_equal [], Topic.validators_on(:author_name)
+ end
+
+ def test_validations_on_the_instance_level
+ Topic.validates :title, :author_name, presence: true
+ Topic.validates :content, length: { minimum: 10 }
+
+ topic = Topic.new
+ assert topic.invalid?
+ assert_equal 3, topic.errors.size
+
+ topic.title = 'Some Title'
+ topic.author_name = 'Some Author'
+ topic.content = 'Some Content Whose Length is more than 10.'
+ assert topic.valid?
+ end
+
+ def test_validate
+ Topic.validate do
+ validates_presence_of :title, :author_name
+ validates_length_of :content, minimum: 10
+ end
+
+ topic = Topic.new
+ assert_empty topic.errors
+
+ topic.validate
+ assert_not_empty topic.errors
+ end
+
+ def test_strict_validation_in_validates
+ Topic.validates :title, strict: true, presence: true
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_strict_validation_not_fails
+ Topic.validates :title, strict: true, presence: true
+ assert Topic.new(title: "hello").valid?
+ end
+
+ def test_strict_validation_particular_validator
+ Topic.validates :title, presence: { strict: true }
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_strict_validation_in_custom_validator_helper
+ Topic.validates_presence_of :title, strict: true
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_strict_validation_custom_exception
+ Topic.validates_presence_of :title, strict: CustomStrictValidationException
+ assert_raises CustomStrictValidationException do
+ Topic.new.valid?
+ end
+ end
+
+ def test_validates_with_bang
+ Topic.validates! :title, presence: true
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_validates_with_false_hash_value
+ Topic.validates :title, presence: false
+ assert Topic.new.valid?
+ end
+
+ def test_strict_validation_error_message
+ Topic.validates :title, strict: true, presence: true
+
+ exception = assert_raises(ActiveModel::StrictValidationFailed) do
+ Topic.new.valid?
+ end
+ assert_equal "Title can't be blank", exception.message
+ end
+
+ def test_does_not_modify_options_argument
+ options = { presence: true }
+ Topic.validates :title, options
+ assert_equal({ presence: true }, options)
+ end
+
+ def test_dup_validity_is_independent
+ Topic.validates_presence_of :title
+ topic = Topic.new("title" => "Literature")
+ topic.valid?
+
+ duped = topic.dup
+ duped.title = nil
+ assert duped.invalid?
+
+ topic.title = nil
+ duped.title = 'Mathematics'
+ assert topic.invalid?
+ assert duped.valid?
+ end
+end
diff --git a/activemodel/test/config.rb b/activemodel/test/config.rb
new file mode 100644
index 0000000000..0b577a9936
--- /dev/null
+++ b/activemodel/test/config.rb
@@ -0,0 +1,3 @@
+TEST_ROOT = File.expand_path(File.dirname(__FILE__))
+FIXTURES_ROOT = TEST_ROOT + "/fixtures"
+SCHEMA_FILE = TEST_ROOT + "/schema.rb"
diff --git a/activemodel/test/models/account.rb b/activemodel/test/models/account.rb
new file mode 100644
index 0000000000..eed668d38f
--- /dev/null
+++ b/activemodel/test/models/account.rb
@@ -0,0 +1,5 @@
+class Account
+ include ActiveModel::ForbiddenAttributesProtection
+
+ public :sanitize_for_mass_assignment
+end
diff --git a/activemodel/test/models/blog_post.rb b/activemodel/test/models/blog_post.rb
new file mode 100644
index 0000000000..46eba857df
--- /dev/null
+++ b/activemodel/test/models/blog_post.rb
@@ -0,0 +1,9 @@
+module Blog
+ def self.use_relative_model_naming?
+ true
+ end
+
+ class Post
+ extend ActiveModel::Naming
+ end
+end
diff --git a/activemodel/test/models/contact.rb b/activemodel/test/models/contact.rb
new file mode 100644
index 0000000000..c25be28e1d
--- /dev/null
+++ b/activemodel/test/models/contact.rb
@@ -0,0 +1,26 @@
+class Contact
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+
+ attr_accessor :id, :name, :age, :created_at, :awesome, :preferences
+
+ def social
+ %w(twitter github)
+ end
+
+ def network
+ { git: :github }
+ end
+
+ def initialize(options = {})
+ options.each { |name, value| send("#{name}=", value) }
+ end
+
+ def pseudonyms
+ nil
+ end
+
+ def persisted?
+ id
+ end
+end
diff --git a/activemodel/test/models/custom_reader.rb b/activemodel/test/models/custom_reader.rb
new file mode 100644
index 0000000000..2fbcf79c3d
--- /dev/null
+++ b/activemodel/test/models/custom_reader.rb
@@ -0,0 +1,15 @@
+class CustomReader
+ include ActiveModel::Validations
+
+ def initialize(data = {})
+ @data = data
+ end
+
+ def []=(key, value)
+ @data[key] = value
+ end
+
+ def read_attribute_for_validation(key)
+ @data[key]
+ end
+end \ No newline at end of file
diff --git a/activemodel/test/models/helicopter.rb b/activemodel/test/models/helicopter.rb
new file mode 100644
index 0000000000..933f3c463a
--- /dev/null
+++ b/activemodel/test/models/helicopter.rb
@@ -0,0 +1,7 @@
+class Helicopter
+ include ActiveModel::Conversion
+end
+
+class Helicopter::Comanche
+ include ActiveModel::Conversion
+end
diff --git a/activemodel/test/models/person.rb b/activemodel/test/models/person.rb
new file mode 100644
index 0000000000..e896e90f98
--- /dev/null
+++ b/activemodel/test/models/person.rb
@@ -0,0 +1,17 @@
+class Person
+ include ActiveModel::Validations
+ extend ActiveModel::Translation
+
+ attr_accessor :title, :karma, :salary, :gender
+
+ def condition_is_true
+ true
+ end
+end
+
+class Person::Gender
+ extend ActiveModel::Translation
+end
+
+class Child < Person
+end
diff --git a/activemodel/test/models/person_with_validator.rb b/activemodel/test/models/person_with_validator.rb
new file mode 100644
index 0000000000..505ed880c1
--- /dev/null
+++ b/activemodel/test/models/person_with_validator.rb
@@ -0,0 +1,24 @@
+class PersonWithValidator
+ include ActiveModel::Validations
+
+ class PresenceValidator < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ record.errors[attribute] << "Local validator#{options[:custom]}" if value.blank?
+ end
+ end
+
+ class LikeValidator < ActiveModel::EachValidator
+ def initialize(options)
+ @with = options[:with]
+ super
+ end
+
+ def validate_each(record, attribute, value)
+ unless value[@with]
+ record.errors.add attribute, "does not appear to be like #{@with}"
+ end
+ end
+ end
+
+ attr_accessor :title, :karma
+end
diff --git a/activemodel/test/models/project.rb b/activemodel/test/models/project.rb
new file mode 100644
index 0000000000..581b6dc0b3
--- /dev/null
+++ b/activemodel/test/models/project.rb
@@ -0,0 +1,3 @@
+class Project
+ include ActiveModel::DeprecatedMassAssignmentSecurity
+end
diff --git a/activemodel/test/models/reply.rb b/activemodel/test/models/reply.rb
new file mode 100644
index 0000000000..b77910e671
--- /dev/null
+++ b/activemodel/test/models/reply.rb
@@ -0,0 +1,32 @@
+require 'models/topic'
+
+class Reply < Topic
+ validate :errors_on_empty_content
+ validate :title_is_wrong_create, on: :create
+
+ validate :check_empty_title
+ validate :check_content_mismatch, on: :create
+ validate :check_wrong_update, on: :update
+
+ def check_empty_title
+ errors[:title] << "is Empty" unless title && title.size > 0
+ end
+
+ def errors_on_empty_content
+ errors[:content] << "is Empty" unless content && content.size > 0
+ end
+
+ def check_content_mismatch
+ if title && content && content == "Mismatch"
+ errors[:title] << "is Content Mismatch"
+ end
+ end
+
+ def title_is_wrong_create
+ errors[:title] << "is Wrong Create" if title && title == "Wrong Create"
+ end
+
+ def check_wrong_update
+ errors[:title] << "is Wrong Update" if title && title == "Wrong Update"
+ end
+end
diff --git a/activemodel/test/models/sheep.rb b/activemodel/test/models/sheep.rb
new file mode 100644
index 0000000000..7aba055c4f
--- /dev/null
+++ b/activemodel/test/models/sheep.rb
@@ -0,0 +1,3 @@
+class Sheep
+ extend ActiveModel::Naming
+end
diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb
new file mode 100644
index 0000000000..1411a093e9
--- /dev/null
+++ b/activemodel/test/models/topic.rb
@@ -0,0 +1,40 @@
+class Topic
+ include ActiveModel::Validations
+ include ActiveModel::Validations::Callbacks
+
+ def self._validates_default_keys
+ super | [ :message ]
+ end
+
+ attr_accessor :title, :author_name, :content, :approved, :created_at
+ attr_accessor :after_validation_performed
+
+ after_validation :perform_after_validation
+
+ def initialize(attributes = {})
+ attributes.each do |key, value|
+ send "#{key}=", value
+ end
+ end
+
+ def condition_is_true
+ true
+ end
+
+ def condition_is_true_but_its_not
+ false
+ end
+
+ def perform_after_validation
+ self.after_validation_performed = true
+ end
+
+ def my_validation
+ errors.add :title, "is missing" unless title
+ end
+
+ def my_validation_with_arg(attr)
+ errors.add attr, "is missing" unless send(attr)
+ end
+
+end
diff --git a/activemodel/test/models/track_back.rb b/activemodel/test/models/track_back.rb
new file mode 100644
index 0000000000..768c96ecf0
--- /dev/null
+++ b/activemodel/test/models/track_back.rb
@@ -0,0 +1,11 @@
+class Post
+ class TrackBack
+ def to_model
+ NamedTrackBack.new
+ end
+ end
+
+ class NamedTrackBack
+ extend ActiveModel::Naming
+ end
+end \ No newline at end of file
diff --git a/activemodel/test/models/user.rb b/activemodel/test/models/user.rb
new file mode 100644
index 0000000000..1ec6001c48
--- /dev/null
+++ b/activemodel/test/models/user.rb
@@ -0,0 +1,10 @@
+class User
+ extend ActiveModel::Callbacks
+ include ActiveModel::SecurePassword
+
+ define_model_callbacks :create
+
+ has_secure_password
+
+ attr_accessor :password_digest
+end
diff --git a/activemodel/test/models/visitor.rb b/activemodel/test/models/visitor.rb
new file mode 100644
index 0000000000..22ad1a3c3d
--- /dev/null
+++ b/activemodel/test/models/visitor.rb
@@ -0,0 +1,10 @@
+class Visitor
+ extend ActiveModel::Callbacks
+ include ActiveModel::SecurePassword
+
+ define_model_callbacks :create
+
+ has_secure_password(validations: false)
+
+ attr_accessor :password_digest, :password_confirmation
+end
diff --git a/activemodel/test/validators/email_validator.rb b/activemodel/test/validators/email_validator.rb
new file mode 100644
index 0000000000..cff47ac230
--- /dev/null
+++ b/activemodel/test/validators/email_validator.rb
@@ -0,0 +1,6 @@
+class EmailValidator < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ record.errors[attribute] << (options[:message] || "is not an email") unless
+ value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
+ end
+end \ No newline at end of file
diff --git a/activemodel/test/validators/namespace/email_validator.rb b/activemodel/test/validators/namespace/email_validator.rb
new file mode 100644
index 0000000000..57e2793ce2
--- /dev/null
+++ b/activemodel/test/validators/namespace/email_validator.rb
@@ -0,0 +1,6 @@
+require 'validators/email_validator'
+
+module Namespace
+ class EmailValidator < ::EmailValidator
+ end
+end