diff options
Diffstat (limited to 'activemodel/test')
31 files changed, 460 insertions, 115 deletions
diff --git a/activemodel/test/cases/attribute_assignment_test.rb b/activemodel/test/cases/attribute_assignment_test.rb new file mode 100644 index 0000000000..402caf21f7 --- /dev/null +++ b/activemodel/test/cases/attribute_assignment_test.rb @@ -0,0 +1,107 @@ +require "cases/helper" +require "active_support/hash_with_indifferent_access" + +class AttributeAssignmentTest < ActiveModel::TestCase + class Model + include ActiveModel::AttributeAssignment + + attr_accessor :name, :description + + def initialize(attributes = {}) + assign_attributes(attributes) + end + + def broken_attribute=(value) + raise ErrorFromAttributeWriter + end + + protected + + attr_writer :metadata + end + + class ErrorFromAttributeWriter < StandardError + end + + class ProtectedParams < ActiveSupport::HashWithIndifferentAccess + def permit! + @permitted = true + end + + def permitted? + @permitted ||= false + end + + def dup + super.tap do |duplicate| + duplicate.instance_variable_set :@permitted, permitted? + end + end + end + + test "simple assignment" do + model = Model.new + + model.assign_attributes(name: "hello", description: "world") + assert_equal "hello", model.name + assert_equal "world", model.description + end + + test "assign non-existing attribute" do + model = Model.new + error = assert_raises(ActiveModel::AttributeAssignment::UnknownAttributeError) do + model.assign_attributes(hz: 1) + end + + assert_equal model, error.record + assert_equal "hz", error.attribute + end + + test "assign private attribute" do + model = Model.new + assert_raises(ActiveModel::AttributeAssignment::UnknownAttributeError) do + model.assign_attributes(metadata: { a: 1 }) + end + end + + test "does not swallow errors raised in an attribute writer" do + assert_raises(ErrorFromAttributeWriter) do + Model.new(broken_attribute: 1) + end + end + + test "an ArgumentError is raised if a non-hash-like obejct is passed" do + assert_raises(ArgumentError) do + Model.new(1) + end + end + + test "forbidden attributes cannot be used for mass assignment" do + params = ProtectedParams.new(name: "Guille", description: "m") + + assert_raises(ActiveModel::ForbiddenAttributesError) do + Model.new(params) + end + end + + test "permitted attributes can be used for mass assignment" do + params = ProtectedParams.new(name: "Guille", description: "desc") + params.permit! + model = Model.new(params) + + assert_equal "Guille", model.name + assert_equal "desc", model.description + end + + test "regular hash should still be used for mass assignment" do + model = Model.new(name: "Guille", description: "m") + + assert_equal "Guille", model.name + assert_equal "m", model.description + end + + test "assigning no attributes should not raise, even if the hash is un-permitted" do + model = Model.new + assert_nil model.assign_attributes(ProtectedParams.new({})) + end +end diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb index 5fede098d1..85455c112c 100644 --- a/activemodel/test/cases/callbacks_test.rb +++ b/activemodel/test/cases/callbacks_test.rb @@ -7,6 +7,7 @@ class CallbacksTest < ActiveModel::TestCase model.callbacks << :before_around_create yield model.callbacks << :after_around_create + false end end @@ -24,16 +25,22 @@ class CallbacksTest < ActiveModel::TestCase after_create do |model| model.callbacks << :after_create + false end after_create "@callbacks << :final_callback" - def initialize(valid=true) - @callbacks, @valid = [], valid + def initialize(options = {}) + @callbacks = [] + @valid = options[:valid] + @before_create_returns = options.fetch(:before_create_returns, true) + @before_create_throws = options[:before_create_throws] end def before_create @callbacks << :before_create + throw(@before_create_throws) if @before_create_throws + @before_create_returns end def create @@ -51,14 +58,28 @@ class CallbacksTest < ActiveModel::TestCase :after_around_create, :after_create, :final_callback] end - test "after callbacks are always appended" do + test "the callback chain is not halted when around or after callbacks return false" do model = ModelCallbacks.new model.create assert_equal model.callbacks.last, :final_callback end + test "the callback chain is halted when a before callback returns false (deprecated)" do + model = ModelCallbacks.new(before_create_returns: false) + assert_deprecated do + model.create + assert_equal model.callbacks.last, :before_create + end + end + + test "the callback chain is halted when a callback throws :abort" do + model = ModelCallbacks.new(before_create_throws: :abort) + model.create + assert_equal model.callbacks, [:before_create] + end + test "after callbacks are not executed if the block returns false" do - model = ModelCallbacks.new(false) + model = ModelCallbacks.new(valid: false) model.create assert_equal model.callbacks, [ :before_create, :before_around_create, :create, :after_around_create] diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb index 2853476c91..66ed8a350a 100644 --- a/activemodel/test/cases/dirty_test.rb +++ b/activemodel/test/cases/dirty_test.rb @@ -43,7 +43,7 @@ class DirtyTest < ActiveModel::TestCase end def reload - reset_changes + clear_changes_information end end @@ -107,7 +107,7 @@ class DirtyTest < ActiveModel::TestCase test "resetting attribute" do @model.name = "Bob" - @model.reset_name! + @model.restore_name! assert_nil @model.name assert !@model.name_changed? end @@ -176,4 +176,32 @@ class DirtyTest < ActiveModel::TestCase 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 index 42d0365521..17dbb817d0 100644 --- a/activemodel/test/cases/errors_test.rb +++ b/activemodel/test/cases/errors_test.rb @@ -59,6 +59,17 @@ class ErrorsTest < ActiveModel::TestCase assert_equal false, errors.has_key?(:name), 'errors should not have key :name' end + def test_key? + errors = ActiveModel::Errors.new(self) + errors[:foo] = 'omg' + assert_equal true, errors.key?(:foo), 'errors should have key :foo' + end + + def test_no_key + errors = ActiveModel::Errors.new(self) + assert_equal false, errors.key?(:name), 'errors should not have key :name' + end + test "clear errors" do person = Person.new person.validate! @@ -312,4 +323,46 @@ class ErrorsTest < ActiveModel::TestCase person.errors.expects(:generate_message).with(:name, :blank, { message: 'custom' }) person.errors.add_on_blank :name, message: 'custom' end + + test "details returns added error detail" do + person = Person.new + person.errors.add(:name, :invalid) + assert_equal({ name: [{ error: :invalid }] }, person.errors.details) + end + + test "details returns added error detail with custom option" do + person = Person.new + person.errors.add(:name, :greater_than, count: 5) + assert_equal({ name: [{ error: :greater_than, count: 5 }] }, person.errors.details) + end + + test "details do not include message option" do + person = Person.new + person.errors.add(:name, :invalid, message: "is bad") + assert_equal({ name: [{ error: :invalid }] }, person.errors.details) + end + + test "dup duplicates details" do + errors = ActiveModel::Errors.new(Person.new) + errors.add(:name, :invalid) + errors_dup = errors.dup + errors_dup.add(:name, :taken) + assert_not_equal errors_dup.details, errors.details + end + + test "delete removes details on given attribute" do + errors = ActiveModel::Errors.new(Person.new) + errors.add(:name, :invalid) + errors.delete(:name) + assert_empty errors.details[:name] + end + + test "clear removes details" do + person = Person.new + person.errors.add(:name, :invalid) + + assert_equal 1, person.errors.details.count + person.errors.clear + assert person.errors.details.empty? + end end diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb index 522a7cebb4..4ce6103593 100644 --- a/activemodel/test/cases/helper.rb +++ b/activemodel/test/cases/helper.rb @@ -11,3 +11,10 @@ ActiveSupport::Deprecation.debug = true I18n.enforce_available_locales = false require 'active_support/testing/autorun' + +require 'mocha/setup' # FIXME: stop using mocha + +# FIXME: we have tests that depend on run order, we should fix that and +# remove this method call. +require 'active_support/test_case' +ActiveSupport::TestCase.test_order = :sorted diff --git a/activemodel/test/cases/model_test.rb b/activemodel/test/cases/model_test.rb index ee0fa26546..9a8d873ec9 100644 --- a/activemodel/test/cases/model_test.rb +++ b/activemodel/test/cases/model_test.rb @@ -70,6 +70,8 @@ class ModelTest < ActiveModel::TestCase end def test_mixin_initializer_when_args_dont_exist - assert_raises(NoMethodError) { SimpleModel.new(hello: 'world') } + assert_raises(ActiveModel::AttributeAssignment::UnknownAttributeError) do + SimpleModel.new(hello: 'world') + end end end diff --git a/activemodel/test/cases/naming_test.rb b/activemodel/test/cases/naming_test.rb index aa683f4152..7b8287edbf 100644 --- a/activemodel/test/cases/naming_test.rb +++ b/activemodel/test/cases/naming_test.rb @@ -272,3 +272,9 @@ class NameWithAnonymousClassTest < ActiveModel::TestCase 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/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb index bcd1e04a0f..6d56c8344a 100644 --- a/activemodel/test/cases/secure_password_test.rb +++ b/activemodel/test/cases/secure_password_test.rb @@ -20,15 +20,29 @@ class SecurePasswordTest < ActiveModel::TestCase ActiveModel::SecurePassword.min_cost = @original_min_cost end - test "create and updating without validations" do - assert @visitor.valid?(:create), 'visitor should be valid' - assert @visitor.valid?(:update), 'visitor should be valid' + 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 - @visitor.password = '123' - @visitor.password_confirmation = '456' + 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' - assert @visitor.valid?(:create), 'visitor should be valid' - assert @visitor.valid?(:update), 'visitor 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 @@ -45,6 +59,14 @@ class SecurePasswordTest < ActiveModel::TestCase 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 = '' @@ -67,15 +89,19 @@ class SecurePasswordTest < ActiveModel::TestCase assert_equal ["doesn't match Password"], @user.errors[:password_confirmation] end - test "create a new user with validation and a correct 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] + 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 validation and no change in password" do + 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 @@ -84,6 +110,11 @@ class SecurePasswordTest < ActiveModel::TestCase 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 = '' @@ -97,6 +128,14 @@ class SecurePasswordTest < ActiveModel::TestCase 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 = '' @@ -119,14 +158,6 @@ class SecurePasswordTest < ActiveModel::TestCase assert_equal ["doesn't match Password"], @existing_user.errors[:password_confirmation] end - test "updating an existing user with validation and a correct 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' diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb index 60414a6570..e2eb91eeb0 100644 --- a/activemodel/test/cases/serializers/json_serialization_test.rb +++ b/activemodel/test/cases/serializers/json_serialization_test.rb @@ -1,25 +1,7 @@ require 'cases/helper' require 'models/contact' -require 'models/automobile' 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 diff --git a/activemodel/test/cases/serializers/xml_serialization_test.rb b/activemodel/test/cases/serializers/xml_serialization_test.rb index 5db14c8157..22fca5bd17 100644 --- a/activemodel/test/cases/serializers/xml_serialization_test.rb +++ b/activemodel/test/cases/serializers/xml_serialization_test.rb @@ -3,18 +3,6 @@ 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 diff --git a/activemodel/test/cases/validations/absence_validation_test.rb b/activemodel/test/cases/validations/absence_validation_test.rb index 795ce16d28..9cbc77dfb5 100644 --- a/activemodel/test/cases/validations/absence_validation_test.rb +++ b/activemodel/test/cases/validations/absence_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' require 'models/person' @@ -11,7 +10,7 @@ class AbsenceValidationTest < ActiveModel::TestCase CustomReader.clear_validators! end - def test_validate_absences + def test_validates_absence_of Topic.validates_absence_of(:title, :content) t = Topic.new t.title = "foo" @@ -23,11 +22,12 @@ class AbsenceValidationTest < ActiveModel::TestCase 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_accepts_array_arguments + def test_validates_absence_of_with_array_arguments Topic.validates_absence_of %w(title content) t = Topic.new t.title = "foo" @@ -37,7 +37,7 @@ class AbsenceValidationTest < ActiveModel::TestCase assert_equal ["must be blank"], t.errors[:content] end - def test_validates_acceptance_of_with_custom_error_using_quotes + 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" diff --git a/activemodel/test/cases/validations/acceptance_validation_test.rb b/activemodel/test/cases/validations/acceptance_validation_test.rb index e78aa1adaf..9c2114d83d 100644 --- a/activemodel/test/cases/validations/acceptance_validation_test.rb +++ b/activemodel/test/cases/validations/acceptance_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' @@ -65,4 +64,10 @@ class AcceptanceValidationTest < ActiveModel::TestCase ensure Person.clear_validators! end + + def test_validates_acceptance_of_true + Topic.validates_acceptance_of(:terms_of_service) + + assert Topic.new(terms_of_service: true).valid? + end end diff --git a/activemodel/test/cases/validations/callbacks_test.rb b/activemodel/test/cases/validations/callbacks_test.rb index 6cd0f4ed4d..75eb18e795 100644 --- a/activemodel/test/cases/validations/callbacks_test.rb +++ b/activemodel/test/cases/validations/callbacks_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' class Dog @@ -30,16 +29,34 @@ class DogWithTwoValidators < Dog before_validation { self.history << 'before_validation_marker2' } end -class DogValidatorReturningFalse < Dog +class DogDeprecatedBeforeValidatorReturningFalse < Dog before_validation { false } before_validation { self.history << 'before_validation_marker2' } end +class DogBeforeValidatorThrowingAbort < Dog + before_validation { throw :abort } + before_validation { self.history << 'before_validation_marker2' } +end + +class DogAfterValidatorReturningFalse < Dog + after_validation { false } + after_validation { self.history << 'after_validation_marker' } +end + class DogWithMissingName < Dog before_validation { self.history << 'before_validation_marker' } validates_presence_of :name end +class DogValidatorWithOnCondition < Dog + before_validation :set_before_validation_marker, on: :create + after_validation :set_after_validation_marker, on: :create + + def set_before_validation_marker; self.history << 'before_validation_marker'; end + def set_after_validation_marker; self.history << 'after_validation_marker' ; end +end + class DogValidatorWithIfCondition < Dog before_validation :set_before_validation_marker1, if: -> { true } before_validation :set_before_validation_marker2, if: -> { false } @@ -63,6 +80,24 @@ class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase assert_equal ["before_validation_marker1", "after_validation_marker1"], d.history end + def test_on_condition_is_respected_for_validation_with_matching_context + d = DogValidatorWithOnCondition.new + d.valid?(:create) + assert_equal ["before_validation_marker", "after_validation_marker"], d.history + end + + def test_on_condition_is_respected_for_validation_without_matching_context + d = DogValidatorWithOnCondition.new + d.valid?(:save) + assert_equal [], d.history + end + + def test_on_condition_is_respected_for_validation_without_context + d = DogValidatorWithOnCondition.new + d.valid? + assert_equal [], d.history + end + def test_before_validation_and_after_validation_callbacks_should_be_called d = DogWithMethodCallbacks.new d.valid? @@ -81,13 +116,28 @@ class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase 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 + def test_further_callbacks_should_not_be_called_if_before_validation_throws_abort + d = DogBeforeValidatorThrowingAbort.new output = d.valid? assert_equal [], d.history assert_equal false, output end + def test_deprecated_further_callbacks_should_not_be_called_if_before_validation_returns_false + d = DogDeprecatedBeforeValidatorReturningFalse.new + assert_deprecated do + output = d.valid? + assert_equal [], d.history + assert_equal false, output + end + end + + def test_further_callbacks_should_be_called_if_after_validation_returns_false + d = DogAfterValidatorReturningFalse.new + d.valid? + assert_equal ['after_validation_marker'], d.history + end + def test_validation_test_should_be_done d = DogWithMissingName.new output = d.valid? diff --git a/activemodel/test/cases/validations/conditional_validation_test.rb b/activemodel/test/cases/validations/conditional_validation_test.rb index 1261937b56..296d3b4407 100644 --- a/activemodel/test/cases/validations/conditional_validation_test.rb +++ b/activemodel/test/cases/validations/conditional_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' diff --git a/activemodel/test/cases/validations/confirmation_validation_test.rb b/activemodel/test/cases/validations/confirmation_validation_test.rb index 65a2a1eb49..c1431548f7 100644 --- a/activemodel/test/cases/validations/confirmation_validation_test.rb +++ b/activemodel/test/cases/validations/confirmation_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb index 1ce41f9bc9..b269c3691a 100644 --- a/activemodel/test/cases/validations/exclusion_validation_test.rb +++ b/activemodel/test/cases/validations/exclusion_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' diff --git a/activemodel/test/cases/validations/format_validation_test.rb b/activemodel/test/cases/validations/format_validation_test.rb index 0f91b73cd7..86bbbe6ebe 100644 --- a/activemodel/test/cases/validations/format_validation_test.rb +++ b/activemodel/test/cases/validations/format_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb index 96084a32ba..70ee7afecc 100644 --- a/activemodel/test/cases/validations/i18n_validation_test.rb +++ b/activemodel/test/cases/validations/i18n_validation_test.rb @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - require "cases/helper" require 'models/person' diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb index 3a8f3080e1..55d1fb4dcb 100644 --- a/activemodel/test/cases/validations/inclusion_validation_test.rb +++ b/activemodel/test/cases/validations/inclusion_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'active_support/all' diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb index 046ffcb16f..209903898e 100644 --- a/activemodel/test/cases/validations/length_validation_test.rb +++ b/activemodel/test/cases/validations/length_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' @@ -331,6 +330,19 @@ class LengthValidationTest < ActiveModel::TestCase assert_equal ["Your essay must be at least 5 words."], t.errors[:content] end + + def test_validates_length_of_with_symbol + Topic.validates_length_of :content, minimum: 5, too_short: "Your essay must be at least %{count} words.", + tokenizer: :my_word_tokenizer + 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) diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb index e1657407cf..05432abaff 100644 --- a/activemodel/test/cases/validations/numericality_validation_test.rb +++ b/activemodel/test/cases/validations/numericality_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' @@ -50,6 +49,21 @@ class NumericalityValidationTest < ActiveModel::TestCase 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(&: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 @@ -115,7 +129,7 @@ class NumericalityValidationTest < ActiveModel::TestCase 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 } + Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new(&:min_approved) invalid!([3, 4]) valid!([5, 6]) diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb index ecf16d1e16..59b9db0795 100644 --- a/activemodel/test/cases/validations/presence_validation_test.rb +++ b/activemodel/test/cases/validations/presence_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' diff --git a/activemodel/test/cases/validations/validates_test.rb b/activemodel/test/cases/validations/validates_test.rb index 699a872e42..04101f3545 100644 --- a/activemodel/test/cases/validations/validates_test.rb +++ b/activemodel/test/cases/validations/validates_test.rb @@ -1,9 +1,7 @@ -# 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 diff --git a/activemodel/test/cases/validations/validations_context_test.rb b/activemodel/test/cases/validations/validations_context_test.rb index 005bf118c6..150dce379f 100644 --- a/activemodel/test/cases/validations/validations_context_test.rb +++ b/activemodel/test/cases/validations/validations_context_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb index 736c2deea8..01804032f0 100644 --- a/activemodel/test/cases/validations/with_validation_test.rb +++ b/activemodel/test/cases/validations/with_validation_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb index 4fee704ef5..dc125bc884 100644 --- a/activemodel/test/cases/validations_test.rb +++ b/activemodel/test/cases/validations_test.rb @@ -1,10 +1,8 @@ -# encoding: utf-8 require 'cases/helper' require 'models/topic' require 'models/reply' require 'models/custom_reader' -require 'models/automobile' require 'active_support/json' require 'active_support/xml_mini' @@ -19,11 +17,11 @@ class ValidationsTest < ActiveModel::TestCase 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.invalid?, "A reply without content should be invalid" 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.valid?, "A reply with content should be valid" assert r.after_validation_performed, "after_validation callback should be called" end @@ -167,6 +165,50 @@ class ValidationsTest < ActiveModel::TestCase end end + def test_invalid_options_to_validate + error = assert_raises(ArgumentError) do + # A common mistake -- we meant to call 'validates' + Topic.validate :title, presence: true + end + message = 'Unknown key: :presence. Valid keys are: :on, :if, :unless, :prepend. Perhaps you meant to call `validates` instead of `validate`?' + assert_equal message, error.message + end + + def test_callback_options_to_validate + klass = Class.new(Topic) do + attr_reader :call_sequence + + def initialize(*) + super + @call_sequence = [] + end + + private + def validator_a + @call_sequence << :a + end + + def validator_b + @call_sequence << :b + end + + def validator_c + @call_sequence << :c + end + end + + assert_nothing_raised do + klass.validate :validator_a, if: ->{ true } + klass.validate :validator_b, prepend: true + klass.validate :validator_c, unless: ->{ true } + end + + t = klass.new + + assert_predicate t, :valid? + assert_equal [:b, :a], t.call_sequence + end + def test_errors_conversions Topic.validates_presence_of %w(title content) t = Topic.new @@ -274,7 +316,7 @@ class ValidationsTest < ActiveModel::TestCase ActiveModel::Validations::FormatValidator, ActiveModel::Validations::LengthValidator, ActiveModel::Validations::PresenceValidator - ], validators.map { |v| v.class }.sort_by { |c| c.to_s } + ], validators.map(&:class).sort_by(&:to_s) end def test_list_of_validators_will_be_empty_when_empty @@ -283,25 +325,30 @@ class ValidationsTest < ActiveModel::TestCase end def test_validations_on_the_instance_level - auto = Automobile.new - - assert auto.invalid? - assert_equal 3, auto.errors.size + Topic.validates :title, :author_name, presence: true + Topic.validates :content, length: { minimum: 10 } - auto.make = 'Toyota' - auto.model = 'Corolla' - auto.approved = '1' + topic = Topic.new + assert topic.invalid? + assert_equal 3, topic.errors.size - assert auto.valid? + 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 - auto = Automobile.new + Topic.validate do + validates_presence_of :title, :author_name + validates_length_of :content, minimum: 10 + end - assert_empty auto.errors + topic = Topic.new + assert_empty topic.errors - auto.validate - assert_not_empty auto.errors + topic.validate + assert_not_empty topic.errors end def test_strict_validation_in_validates diff --git a/activemodel/test/models/automobile.rb b/activemodel/test/models/automobile.rb deleted file mode 100644 index 4df2fe8b3a..0000000000 --- a/activemodel/test/models/automobile.rb +++ /dev/null @@ -1,13 +0,0 @@ -class Automobile - include ActiveModel::Validations - - validate :validations - - attr_accessor :make, :model, :approved - - def validations - validates_presence_of :make - validates_length_of :model, within: 2..10 - validates_acceptance_of :approved, allow_nil: false - end -end diff --git a/activemodel/test/models/contact.rb b/activemodel/test/models/contact.rb index c25be28e1d..bcfd267a34 100644 --- a/activemodel/test/models/contact.rb +++ b/activemodel/test/models/contact.rb @@ -1,8 +1,13 @@ class Contact extend ActiveModel::Naming include ActiveModel::Conversion + include ActiveModel::Validations + + include ActiveModel::Serializers::JSON + include ActiveModel::Serializers::Xml attr_accessor :id, :name, :age, :created_at, :awesome, :preferences + attr_accessor :address, :friends, :contact def social %w(twitter github) @@ -23,4 +28,14 @@ class Contact def persisted? id end + + def attributes=(hash) + hash.each do |k, v| + instance_variable_set("@#{k}", v) + end + end + + def attributes + instance_values.except("address", "friends", "contact") + end end diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb index 1411a093e9..fed50bc361 100644 --- a/activemodel/test/models/topic.rb +++ b/activemodel/test/models/topic.rb @@ -37,4 +37,8 @@ class Topic errors.add attr, "is missing" unless send(attr) end + def my_word_tokenizer(str) + str.scan(/\w+/) + end + end diff --git a/activemodel/test/models/user.rb b/activemodel/test/models/user.rb index cbe259b1ad..1ec6001c48 100644 --- a/activemodel/test/models/user.rb +++ b/activemodel/test/models/user.rb @@ -1,6 +1,5 @@ class User extend ActiveModel::Callbacks - include ActiveModel::Validations include ActiveModel::SecurePassword define_model_callbacks :create diff --git a/activemodel/test/models/visitor.rb b/activemodel/test/models/visitor.rb index 4d7f4be097..22ad1a3c3d 100644 --- a/activemodel/test/models/visitor.rb +++ b/activemodel/test/models/visitor.rb @@ -1,6 +1,5 @@ class Visitor extend ActiveModel::Callbacks - include ActiveModel::Validations include ActiveModel::SecurePassword define_model_callbacks :create |