1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Convert ActiveModel to 1.9 hash syntax.

I also attempted to fix other styleguide violations such as
{ a: :b } over {a: :b} and foo(b: 'bar') over foo( b: 'bar' ).
This commit is contained in:
Patrick Robertson 2013-05-01 17:10:06 -07:00
parent dd1f36078e
commit eebb9ddf9b
43 changed files with 351 additions and 349 deletions

View file

@ -343,7 +343,7 @@ module ActiveModel
# significantly (in our case our test suite finishes 10% faster with # significantly (in our case our test suite finishes 10% faster with
# this cache). # this cache).
def attribute_method_matchers_cache #:nodoc: def attribute_method_matchers_cache #:nodoc:
@attribute_method_matchers_cache ||= ThreadSafe::Cache.new(:initial_capacity => 4) @attribute_method_matchers_cache ||= ThreadSafe::Cache.new(initial_capacity: 4)
end end
def attribute_method_matcher(method_name) #:nodoc: def attribute_method_matcher(method_name) #:nodoc:

View file

@ -100,10 +100,10 @@ module ActiveModel
def define_model_callbacks(*callbacks) def define_model_callbacks(*callbacks)
options = callbacks.extract_options! options = callbacks.extract_options!
options = { options = {
:terminator => "result == false", terminator: "result == false",
:skip_after_callbacks_if_terminated => true, skip_after_callbacks_if_terminated: true,
:scope => [:kind, :name], scope: [:kind, :name],
:only => [:before, :around, :after] only: [:before, :around, :after]
}.merge!(options) }.merge!(options)
types = Array(options.delete(:only)) types = Array(options.delete(:only))

View file

@ -91,7 +91,7 @@ module ActiveModel
included do included do
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was' attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
attribute_method_affix :prefix => 'reset_', :suffix => '!' attribute_method_affix prefix: 'reset_', suffix: '!'
end end
# Returns +true+ if any attribute have unsaved changes, +false+ otherwise. # Returns +true+ if any attribute have unsaved changes, +false+ otherwise.

View file

@ -231,7 +231,7 @@ module ActiveModel
# # <error>name must be specified</error> # # <error>name must be specified</error>
# # </errors> # # </errors>
def to_xml(options={}) def to_xml(options={})
to_a.to_xml({ :root => "errors", :skip_types => true }.merge!(options)) to_a.to_xml({ root: "errors", skip_types: true }.merge!(options))
end end
# Returns a Hash that can be used as the JSON representation for this # Returns a Hash that can be used as the JSON representation for this
@ -370,11 +370,11 @@ module ActiveModel
def full_message(attribute, message) def full_message(attribute, message)
return message if attribute == :base return message if attribute == :base
attr_name = attribute.to_s.tr('.', '_').humanize attr_name = attribute.to_s.tr('.', '_').humanize
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name) attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
I18n.t(:"errors.format", { I18n.t(:"errors.format", {
:default => "%{attribute} %{message}", default: "%{attribute} %{message}",
:attribute => attr_name, attribute: attr_name,
:message => message message: message
}) })
end end
@ -426,10 +426,10 @@ module ActiveModel
value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil) value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
options = { options = {
:default => defaults, default: defaults,
:model => @base.class.model_name.human, model: @base.class.model_name.human,
:attribute => @base.class.human_attribute_name(attribute), attribute: @base.class.human_attribute_name(attribute),
:value => value value: value
}.merge!(options) }.merge!(options)
I18n.translate(key, options) I18n.translate(key, options)

View file

@ -129,7 +129,7 @@ module ActiveModel
# #
# Equivalent to +to_s+. # Equivalent to +to_s+.
delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s, delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
:to_str, :to => :name :to_str, to: :name
# Returns a new ActiveModel::Name instance. By default, the +namespace+ # Returns a new ActiveModel::Name instance. By default, the +namespace+
# and +name+ option will take the namespace and name of the given class # and +name+ option will take the namespace and name of the given class
@ -183,7 +183,7 @@ module ActiveModel
defaults << options[:default] if options[:default] defaults << options[:default] if options[:default]
defaults << @human defaults << @human
options = { :scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults }.merge!(options.except(:default)) options = { scope: [@klass.i18n_scope, :models], count: 1, default: defaults }.merge!(options.except(:default))
I18n.translate(defaults.shift, options) I18n.translate(defaults.shift, options)
end end

View file

@ -57,7 +57,7 @@ module ActiveModel
if options.fetch(:validations, true) if options.fetch(:validations, true)
validates_confirmation_of :password validates_confirmation_of :password
validates_presence_of :password, :on => :create validates_presence_of :password, on: :create
before_create { raise "Password digest missing on new record" if password_digest.blank? } before_create { raise "Password digest missing on new record" if password_digest.blank? }
end end

View file

@ -79,7 +79,7 @@ module ActiveModel
require 'builder' unless defined? ::Builder require 'builder' unless defined? ::Builder
options[:indent] ||= 2 options[:indent] ||= 2
options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent]) options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
@builder = options[:builder] @builder = options[:builder]
@builder.instruct! unless options[:skip_instruct] @builder.instruct! unless options[:skip_instruct]
@ -88,8 +88,8 @@ module ActiveModel
root = ActiveSupport::XmlMini.rename_key(root, options) root = ActiveSupport::XmlMini.rename_key(root, options)
args = [root] args = [root]
args << {:xmlns => options[:namespace]} if options[:namespace] args << { xmlns: options[:namespace] } if options[:namespace]
args << {:type => options[:type]} if options[:type] && !options[:skip_types] args << { type: options[:type] } if options[:type] && !options[:skip_types]
@builder.tag!(*args) do @builder.tag!(*args) do
add_attributes_and_methods add_attributes_and_methods
@ -132,7 +132,7 @@ module ActiveModel
records = records.to_ary records = records.to_ary
tag = ActiveSupport::XmlMini.rename_key(association.to_s, options) tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
type = options[:skip_types] ? { } : {:type => "array"} type = options[:skip_types] ? { } : { type: "array" }
association_name = association.to_s.singularize association_name = association.to_s.singularize
merged_options[:root] = association_name merged_options[:root] = association_name
@ -145,7 +145,7 @@ module ActiveModel
record_type = {} record_type = {}
else else
record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
record_type = {:type => record_class} record_type = { type: record_class }
end end
record.to_xml merged_options.merge(record_type) record.to_xml merged_options.merge(record_type)

View file

@ -41,7 +41,7 @@ module ActiveModel
# #
# Specify +options+ with additional translating options. # Specify +options+ with additional translating options.
def human_attribute_name(attribute, options = {}) def human_attribute_name(attribute, options = {})
options = { :count => 1 }.merge!(options) options = { count: 1 }.merge!(options)
parts = attribute.to_s.split(".") parts = attribute.to_s.split(".")
attribute = parts.pop attribute = parts.pop
namespace = parts.join("/") unless parts.empty? namespace = parts.join("/") unless parts.empty?

View file

@ -46,7 +46,7 @@ module ActiveModel
include HelperMethods include HelperMethods
attr_accessor :validation_context attr_accessor :validation_context
define_callbacks :validate, :scope => :name define_callbacks :validate, scope: :name
class_attribute :_validators class_attribute :_validators
self._validators = Hash.new { |h,k| h[k] = [] } self._validators = Hash.new { |h,k| h[k] = [] }

View file

@ -3,7 +3,7 @@ module ActiveModel
module Validations module Validations
class AcceptanceValidator < EachValidator # :nodoc: class AcceptanceValidator < EachValidator # :nodoc:
def initialize(options) def initialize(options)
super({ :allow_nil => true, :accept => "1" }.merge!(options)) super({ allow_nil: true, accept: "1" }.merge!(options))
end end
def validate_each(record, attribute, value) def validate_each(record, attribute, value)

View file

@ -22,7 +22,7 @@ module ActiveModel
included do included do
include ActiveSupport::Callbacks include ActiveSupport::Callbacks
define_callbacks :validation, :terminator => "result == false", :skip_after_callbacks_if_terminated => true, :scope => [:kind, :name] define_callbacks :validation, terminator: "result == false", skip_after_callbacks_if_terminated: true, scope: [:kind, :name]
end end
module ClassMethods module ClassMethods

View file

@ -5,7 +5,7 @@ module ActiveModel
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed) if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
human_attribute_name = record.class.human_attribute_name(attribute) human_attribute_name = record.class.human_attribute_name(attribute)
record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(:attribute => human_attribute_name)) record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(attribute: human_attribute_name))
end end
end end

View file

@ -8,7 +8,7 @@ module ActiveModel
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
if include?(record, value) if include?(record, value)
record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(:value => value)) record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(value: value))
end end
end end
end end

View file

@ -29,7 +29,7 @@ module ActiveModel
end end
def record_error(record, attribute, name, value) def record_error(record, attribute, name, value)
record.errors.add(attribute, :invalid, options.except(name).merge!(:value => value)) record.errors.add(attribute, :invalid, options.except(name).merge!(value: value))
end end
def regexp_using_multiline_anchors?(regexp) def regexp_using_multiline_anchors?(regexp)

View file

@ -8,7 +8,7 @@ module ActiveModel
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
unless include?(record, value) unless include?(record, value)
record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(:value => value)) record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(value: value))
end end
end end
end end

View file

@ -3,8 +3,8 @@ module ActiveModel
# == Active \Model Length \Validator # == Active \Model Length \Validator
module Validations module Validations
class LengthValidator < EachValidator # :nodoc: class LengthValidator < EachValidator # :nodoc:
MESSAGES = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long] RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]

View file

@ -2,9 +2,9 @@ module ActiveModel
module Validations module Validations
class NumericalityValidator < EachValidator # :nodoc: class NumericalityValidator < EachValidator # :nodoc:
CHECKS = { :greater_than => :>, :greater_than_or_equal_to => :>=, CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
:equal_to => :==, :less_than => :<, :less_than_or_equal_to => :<=, equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
:odd => :odd?, :even => :even?, :other_than => :!= }.freeze odd: :odd?, even: :even?, other_than: :!= }.freeze
RESERVED_OPTIONS = CHECKS.keys + [:only_integer] RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
@ -47,7 +47,7 @@ module ActiveModel
option_value = record.send(option_value) if option_value.is_a?(Symbol) option_value = record.send(option_value) if option_value.is_a?(Symbol)
unless value.send(CHECKS[option], option_value) unless value.send(CHECKS[option], option_value)
record.errors.add(attr_name, option, filtered_options(value).merge(:count => option_value)) record.errors.add(attr_name, option, filtered_options(value).merge(count: option_value))
end end
end end
end end
@ -73,7 +73,7 @@ module ActiveModel
end end
def filtered_options(value) def filtered_options(value)
options.except(*RESERVED_OPTIONS).merge!(:value => value) options.except(*RESERVED_OPTIONS).merge!(value: value)
end end
end end

View file

@ -159,9 +159,9 @@ module ActiveModel
when Hash when Hash
options options
when Range, Array when Range, Array
{ :in => options } { in: options }
else else
{ :with => options } { with: options }
end end
end end
end end

View file

@ -10,7 +10,7 @@ class ModelWithAttributes
end end
def attributes def attributes
{ :foo => 'value of foo', :baz => 'value of baz' } { foo: 'value of foo', baz: 'value of baz' }
end end
private private
@ -80,7 +80,7 @@ class ModelWithRubyKeywordNamedAttributes
include ActiveModel::AttributeMethods include ActiveModel::AttributeMethods
def attributes def attributes
{ :begin => 'value of begin', :end => 'value of end' } { begin: 'value of begin', end: 'value of end' }
end end
private private

View file

@ -15,9 +15,9 @@ class CallbacksTest < ActiveModel::TestCase
extend ActiveModel::Callbacks extend ActiveModel::Callbacks
define_model_callbacks :create define_model_callbacks :create
define_model_callbacks :initialize, :only => :after define_model_callbacks :initialize, only: :after
define_model_callbacks :multiple, :only => [:before, :around] define_model_callbacks :multiple, only: [:before, :around]
define_model_callbacks :empty, :only => [] define_model_callbacks :empty, only: []
before_create :before_create before_create :before_create
around_create CallbackValidator.new around_create CallbackValidator.new

View file

@ -13,7 +13,7 @@ class ConversionTest < ActiveModel::TestCase
end end
test "to_key default implementation returns the id in an array for persisted records" do test "to_key default implementation returns the id in an array for persisted records" do
assert_equal [1], Contact.new(:id => 1).to_key assert_equal [1], Contact.new(id: 1).to_key
end end
test "to_param default implementation returns nil for new records" do test "to_param default implementation returns nil for new records" do
@ -21,7 +21,7 @@ class ConversionTest < ActiveModel::TestCase
end end
test "to_param default implementation returns a string of ids for persisted records" do test "to_param default implementation returns a string of ids for persisted records" do
assert_equal "1", Contact.new(:id => 1).to_param assert_equal "1", Contact.new(id: 1).to_param
end end
test "to_partial_path default implementation returns a string giving a relative path" do test "to_partial_path default implementation returns a string giving a relative path" do

View file

@ -271,8 +271,8 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_empty generates message with custom default message" do test "add_on_empty generates message with custom default message" do
person = Person.new person = Person.new
person.errors.expects(:generate_message).with(:name, :empty, {:message => 'custom'}) person.errors.expects(:generate_message).with(:name, :empty, { message: 'custom' })
person.errors.add_on_empty :name, :message => 'custom' person.errors.add_on_empty :name, message: 'custom'
end end
test "add_on_empty generates message with empty string value" do test "add_on_empty generates message with empty string value" do
@ -297,7 +297,7 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_blank generates message with custom default message" do test "add_on_blank generates message with custom default message" do
person = Person.new person = Person.new
person.errors.expects(:generate_message).with(:name, :blank, {:message => 'custom'}) person.errors.expects(:generate_message).with(:name, :blank, { message: 'custom' })
person.errors.add_on_blank :name, :message => 'custom' person.errors.add_on_blank :name, message: 'custom'
end end
end end

View file

@ -13,7 +13,7 @@ class ModelTest < ActiveModel::TestCase
end end
def test_initialize_with_params def test_initialize_with_params
object = BasicModel.new(:attr => "value") object = BasicModel.new(attr: "value")
assert_equal object.attr, "value" assert_equal object.attr, "value"
end end
@ -26,7 +26,7 @@ class ModelTest < ActiveModel::TestCase
end end
def test_persisted_is_always_false def test_persisted_is_always_false
object = BasicModel.new(:attr => "value") object = BasicModel.new(attr: "value")
assert object.persisted? == false assert object.persisted? == false
end end
end end

View file

@ -49,32 +49,32 @@ class SerializationTest < ActiveModel::TestCase
def test_method_serializable_hash_should_work_with_only_option def test_method_serializable_hash_should_work_with_only_option
expected = {"name"=>"David"} expected = {"name"=>"David"}
assert_equal expected, @user.serializable_hash(:only => [:name]) assert_equal expected, @user.serializable_hash(only: [:name])
end end
def test_method_serializable_hash_should_work_with_except_option def test_method_serializable_hash_should_work_with_except_option
expected = {"gender"=>"male", "email"=>"david@example.com"} expected = {"gender"=>"male", "email"=>"david@example.com"}
assert_equal expected, @user.serializable_hash(:except => [:name]) assert_equal expected, @user.serializable_hash(except: [:name])
end end
def test_method_serializable_hash_should_work_with_methods_option def test_method_serializable_hash_should_work_with_methods_option
expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "email"=>"david@example.com"} expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "email"=>"david@example.com"}
assert_equal expected, @user.serializable_hash(:methods => [:foo]) assert_equal expected, @user.serializable_hash(methods: [:foo])
end end
def test_method_serializable_hash_should_work_with_only_and_methods def test_method_serializable_hash_should_work_with_only_and_methods
expected = {"foo"=>"i_am_foo"} expected = {"foo"=>"i_am_foo"}
assert_equal expected, @user.serializable_hash(:only => [], :methods => [:foo]) assert_equal expected, @user.serializable_hash(only: [], methods: [:foo])
end end
def test_method_serializable_hash_should_work_with_except_and_methods def test_method_serializable_hash_should_work_with_except_and_methods
expected = {"gender"=>"male", "foo"=>"i_am_foo"} expected = {"gender"=>"male", "foo"=>"i_am_foo"}
assert_equal expected, @user.serializable_hash(:except => [:name, :email], :methods => [:foo]) assert_equal expected, @user.serializable_hash(except: [:name, :email], methods: [:foo])
end end
def test_should_not_call_methods_that_dont_respond def test_should_not_call_methods_that_dont_respond
expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"} expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"}
assert_equal expected, @user.serializable_hash(:methods => [:bar]) assert_equal expected, @user.serializable_hash(methods: [:bar])
end end
def test_should_use_read_attribute_for_serialization def test_should_use_read_attribute_for_serialization
@ -83,26 +83,26 @@ class SerializationTest < ActiveModel::TestCase
end end
expected = { "name" => "Jon" } expected = { "name" => "Jon" }
assert_equal expected, @user.serializable_hash(:only => :name) assert_equal expected, @user.serializable_hash(only: :name)
end end
def test_include_option_with_singular_association def test_include_option_with_singular_association
expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com", expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com",
"address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}} "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}}
assert_equal expected, @user.serializable_hash(:include => :address) assert_equal expected, @user.serializable_hash(include: :address)
end end
def test_include_option_with_plural_association def test_include_option_with_plural_association
expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
"friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'}, "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
{"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]} {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
assert_equal expected, @user.serializable_hash(:include => :friends) assert_equal expected, @user.serializable_hash(include: :friends)
end end
def test_include_option_with_empty_association def test_include_option_with_empty_association
@user.friends = [] @user.friends = []
expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", "friends"=>[]} expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", "friends"=>[]}
assert_equal expected, @user.serializable_hash(:include => :friends) assert_equal expected, @user.serializable_hash(include: :friends)
end end
class FriendList class FriendList
@ -120,7 +120,7 @@ class SerializationTest < ActiveModel::TestCase
expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
"friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'}, "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
{"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]} {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
assert_equal expected, @user.serializable_hash(:include => :friends) assert_equal expected, @user.serializable_hash(include: :friends)
end end
def test_multiple_includes def test_multiple_includes
@ -128,13 +128,13 @@ class SerializationTest < ActiveModel::TestCase
"address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}, "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111},
"friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'}, "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
{"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]} {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
assert_equal expected, @user.serializable_hash(:include => [:address, :friends]) assert_equal expected, @user.serializable_hash(include: [:address, :friends])
end end
def test_include_with_options def test_include_with_options
expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
"address"=>{"street"=>"123 Lane"}} "address"=>{"street"=>"123 Lane"}}
assert_equal expected, @user.serializable_hash(:include => {:address => {:only => "street"}}) assert_equal expected, @user.serializable_hash(include: { address: { only: "street" } })
end end
def test_nested_include def test_nested_include
@ -143,19 +143,19 @@ class SerializationTest < ActiveModel::TestCase
"friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male', "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male',
"friends"=> [{"email"=>"david@example.com", "gender"=>"male", "name"=>"David"}]}, "friends"=> [{"email"=>"david@example.com", "gender"=>"male", "name"=>"David"}]},
{"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female', "friends"=> []}]} {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female', "friends"=> []}]}
assert_equal expected, @user.serializable_hash(:include => {:friends => {:include => :friends}}) assert_equal expected, @user.serializable_hash(include: { friends: { include: :friends } })
end end
def test_only_include def test_only_include
expected = {"name"=>"David", "friends" => [{"name" => "Joe"}, {"name" => "Sue"}]} expected = {"name"=>"David", "friends" => [{"name" => "Joe"}, {"name" => "Sue"}]}
assert_equal expected, @user.serializable_hash(:only => :name, :include => {:friends => {:only => :name}}) assert_equal expected, @user.serializable_hash(only: :name, include: { friends: { only: :name } })
end end
def test_except_include def test_except_include
expected = {"name"=>"David", "email"=>"david@example.com", expected = {"name"=>"David", "email"=>"david@example.com",
"friends"=> [{"name" => 'Joe', "email" => 'joe@example.com'}, "friends"=> [{"name" => 'Joe', "email" => 'joe@example.com'},
{"name" => "Sue", "email" => 'sue@example.com'}]} {"name" => "Sue", "email" => 'sue@example.com'}]}
assert_equal expected, @user.serializable_hash(:except => :gender, :include => {:friends => {:except => :gender}}) assert_equal expected, @user.serializable_hash(except: :gender, include: { friends: { except: :gender } })
end end
def test_multiple_includes_with_options def test_multiple_includes_with_options
@ -163,6 +163,6 @@ class SerializationTest < ActiveModel::TestCase
"address"=>{"street"=>"123 Lane"}, "address"=>{"street"=>"123 Lane"},
"friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'}, "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
{"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]} {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
assert_equal expected, @user.serializable_hash(:include => [{:address => {:only => "street"}}, :friends]) assert_equal expected, @user.serializable_hash(include: [{ address: {only: "street" } }, :friends])
end end
end end

View file

@ -91,7 +91,7 @@ class JsonSerializationTest < ActiveModel::TestCase
end end
test "should allow attribute filtering with only" do test "should allow attribute filtering with only" do
json = @contact.to_json(:only => [:name, :age]) json = @contact.to_json(only: [:name, :age])
assert_match %r{"name":"Konata Izumi"}, json assert_match %r{"name":"Konata Izumi"}, json
assert_match %r{"age":16}, json assert_match %r{"age":16}, json

View file

@ -35,7 +35,7 @@ end
class SerializableContact < Contact class SerializableContact < Contact
def serializable_hash(options={}) def serializable_hash(options={})
super(options.merge(:only => [:name, :age])) super(options.merge(only: [:name, :age]))
end end
end end
@ -70,33 +70,33 @@ class XmlSerializationTest < ActiveModel::TestCase
end end
test "should serialize default root with namespace" do test "should serialize default root with namespace" do
@xml = @contact.to_xml :namespace => "http://xml.rubyonrails.org/contact" @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 xmlns="http://xml.rubyonrails.org/contact">}, @xml
assert_match %r{</contact>$}, @xml assert_match %r{</contact>$}, @xml
end end
test "should serialize custom root" do test "should serialize custom root" do
@xml = @contact.to_xml :root => 'xml_contact' @xml = @contact.to_xml root: 'xml_contact'
assert_match %r{^<xml-contact>}, @xml assert_match %r{^<xml-contact>}, @xml
assert_match %r{</xml-contact>$}, @xml assert_match %r{</xml-contact>$}, @xml
end end
test "should allow undasherized tags" do test "should allow undasherized tags" do
@xml = @contact.to_xml :root => 'xml_contact', :dasherize => false @xml = @contact.to_xml root: 'xml_contact', dasherize: false
assert_match %r{^<xml_contact>}, @xml assert_match %r{^<xml_contact>}, @xml
assert_match %r{</xml_contact>$}, @xml assert_match %r{</xml_contact>$}, @xml
assert_match %r{<created_at}, @xml assert_match %r{<created_at}, @xml
end end
test "should allow camelized tags" do test "should allow camelized tags" do
@xml = @contact.to_xml :root => 'xml_contact', :camelize => true @xml = @contact.to_xml root: 'xml_contact', camelize: true
assert_match %r{^<XmlContact>}, @xml assert_match %r{^<XmlContact>}, @xml
assert_match %r{</XmlContact>$}, @xml assert_match %r{</XmlContact>$}, @xml
assert_match %r{<CreatedAt}, @xml assert_match %r{<CreatedAt}, @xml
end end
test "should allow lower-camelized tags" do test "should allow lower-camelized tags" do
@xml = @contact.to_xml :root => 'xml_contact', :camelize => :lower @xml = @contact.to_xml root: 'xml_contact', camelize: :lower
assert_match %r{^<xmlContact>}, @xml assert_match %r{^<xmlContact>}, @xml
assert_match %r{</xmlContact>$}, @xml assert_match %r{</xmlContact>$}, @xml
assert_match %r{<createdAt}, @xml assert_match %r{<createdAt}, @xml
@ -114,7 +114,7 @@ class XmlSerializationTest < ActiveModel::TestCase
end end
test "should allow skipped types" do test "should allow skipped types" do
@xml = @contact.to_xml :skip_types => true @xml = @contact.to_xml skip_types: true
assert_match %r{<age>25</age>}, @xml assert_match %r{<age>25</age>}, @xml
end end
@ -130,7 +130,7 @@ class XmlSerializationTest < ActiveModel::TestCase
end end
test "should serialize nil" do test "should serialize nil" do
assert_match %r{<pseudonyms nil=\"true\"/>}, @contact.to_xml(:methods => :pseudonyms) assert_match %r{<pseudonyms nil=\"true\"/>}, @contact.to_xml(methods: :pseudonyms)
end end
test "should serialize integer" do test "should serialize integer" do
@ -146,11 +146,11 @@ class XmlSerializationTest < ActiveModel::TestCase
end end
test "should serialize array" do 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) assert_match %r{<social type=\"array\">\s*<social>twitter</social>\s*<social>github</social>\s*</social>}, @contact.to_xml(methods: :social)
end end
test "should serialize hash" do test "should serialize hash" do
assert_match %r{<network>\s*<git type=\"symbol\">github</git>\s*</network>}, @contact.to_xml(:methods => :network) assert_match %r{<network>\s*<git type=\"symbol\">github</git>\s*</network>}, @contact.to_xml(methods: :network)
end end
test "should serialize yaml" do test "should serialize yaml" do
@ -159,29 +159,29 @@ class XmlSerializationTest < ActiveModel::TestCase
test "should call proc on object" do test "should call proc on object" do
proc = Proc.new { |options| options[:builder].tag!('nationality', 'unknown') } proc = Proc.new { |options| options[:builder].tag!('nationality', 'unknown') }
xml = @contact.to_xml(:procs => [ proc ]) xml = @contact.to_xml(procs: [ proc ])
assert_match %r{<nationality>unknown</nationality>}, xml assert_match %r{<nationality>unknown</nationality>}, xml
end end
test 'should supply serializable to second proc argument' do test 'should supply serializable to second proc argument' do
proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) } proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
xml = @contact.to_xml(:procs => [ proc ]) xml = @contact.to_xml(procs: [ proc ])
assert_match %r{<name-reverse>kcats noraa</name-reverse>}, xml assert_match %r{<name-reverse>kcats noraa</name-reverse>}, xml
end end
test "should serialize string correctly when type passed" do test "should serialize string correctly when type passed" do
xml = @contact.to_xml :type => 'Contact' xml = @contact.to_xml type: 'Contact'
assert_match %r{<contact type="Contact">}, xml assert_match %r{<contact type="Contact">}, xml
assert_match %r{<name>aaron stack</name>}, xml assert_match %r{<name>aaron stack</name>}, xml
end end
test "include option with singular association" do test "include option with singular association" do
xml = @contact.to_xml :include => :address, :indent => 0 xml = @contact.to_xml include: :address, indent: 0
assert xml.include?(@contact.address.to_xml(:indent => 0, :skip_instruct => true)) assert xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
end end
test "include option with plural association" do test "include option with plural association" do
xml = @contact.to_xml :include => :friends, :indent => 0 xml = @contact.to_xml include: :friends, indent: 0
assert_match %r{<friends type="array">}, xml assert_match %r{<friends type="array">}, xml
assert_match %r{<friend type="Contact">}, xml assert_match %r{<friend type="Contact">}, xml
end end
@ -198,60 +198,60 @@ class XmlSerializationTest < ActiveModel::TestCase
test "include option with ary" do test "include option with ary" do
@contact.friends = FriendList.new(@contact.friends) @contact.friends = FriendList.new(@contact.friends)
xml = @contact.to_xml :include => :friends, :indent => 0 xml = @contact.to_xml include: :friends, indent: 0
assert_match %r{<friends type="array">}, xml assert_match %r{<friends type="array">}, xml
assert_match %r{<friend type="Contact">}, xml assert_match %r{<friend type="Contact">}, xml
end end
test "multiple includes" do test "multiple includes" do
xml = @contact.to_xml :indent => 0, :skip_instruct => true, :include => [ :address, :friends ] 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 xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
assert_match %r{<friends type="array">}, xml assert_match %r{<friends type="array">}, xml
assert_match %r{<friend type="Contact">}, xml assert_match %r{<friend type="Contact">}, xml
end end
test "include with options" do test "include with options" do
xml = @contact.to_xml :indent => 0, :skip_instruct => true, :include => { :address => { :only => :city } } xml = @contact.to_xml indent: 0, skip_instruct: true, include: { address: { only: :city } }
assert xml.include?(%(><address><city>Springfield</city></address>)) assert xml.include?(%(><address><city>Springfield</city></address>))
end end
test "propagates skip_types option to included associations" do test "propagates skip_types option to included associations" do
xml = @contact.to_xml :include => :friends, :indent => 0, :skip_types => true xml = @contact.to_xml include: :friends, indent: 0, skip_types: true
assert_match %r{<friends>}, xml assert_match %r{<friends>}, xml
assert_match %r{<friend>}, xml assert_match %r{<friend>}, xml
end end
test "propagates skip-types option to included associations and attributes" do test "propagates skip-types option to included associations and attributes" do
xml = @contact.to_xml :skip_types => true, :include => :address, :indent => 0 xml = @contact.to_xml skip_types: true, include: :address, indent: 0
assert_match %r{<address>}, xml assert_match %r{<address>}, xml
assert_match %r{<apt-number>}, xml assert_match %r{<apt-number>}, xml
end end
test "propagates camelize option to included associations and attributes" do test "propagates camelize option to included associations and attributes" do
xml = @contact.to_xml :camelize => true, :include => :address, :indent => 0 xml = @contact.to_xml camelize: true, include: :address, indent: 0
assert_match %r{<Address>}, xml assert_match %r{<Address>}, xml
assert_match %r{<AptNumber type="integer">}, xml assert_match %r{<AptNumber type="integer">}, xml
end end
test "propagates dasherize option to included associations and attributes" do test "propagates dasherize option to included associations and attributes" do
xml = @contact.to_xml :dasherize => false, :include => :address, :indent => 0 xml = @contact.to_xml dasherize: false, include: :address, indent: 0
assert_match %r{<apt_number type="integer">}, xml assert_match %r{<apt_number type="integer">}, xml
end end
test "don't propagate skip_types if skip_types is defined at the included association level" do 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 xml = @contact.to_xml skip_types: true, include: { address: { skip_types: false } }, indent: 0
assert_match %r{<address>}, xml assert_match %r{<address>}, xml
assert_match %r{<apt-number type="integer">}, xml assert_match %r{<apt-number type="integer">}, xml
end end
test "don't propagate camelize if camelize is defined at the included association level" do 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 xml = @contact.to_xml camelize: true, include: { address: { camelize: false } }, indent: 0
assert_match %r{<address>}, xml assert_match %r{<address>}, xml
assert_match %r{<apt-number type="integer">}, xml assert_match %r{<apt-number type="integer">}, xml
end end
test "don't propagate dasherize if dasherize is defined at the included association level" do 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 xml = @contact.to_xml dasherize: false, include: { address: { dasherize: true } }, indent: 0
assert_match %r{<address>}, xml assert_match %r{<address>}, xml
assert_match %r{<apt-number type="integer">}, xml assert_match %r{<apt-number type="integer">}, xml
end end

View file

@ -8,22 +8,22 @@ class ActiveModelI18nTests < ActiveModel::TestCase
end end
def test_translated_model_attributes def test_translated_model_attributes
I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } } I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute' } } }
assert_equal 'person name attribute', Person.human_attribute_name('name') assert_equal 'person name attribute', Person.human_attribute_name('name')
end end
def test_translated_model_attributes_with_default def test_translated_model_attributes_with_default
I18n.backend.store_translations 'en', :attributes => { :name => 'name default attribute' } I18n.backend.store_translations 'en', attributes: { name: 'name default attribute' }
assert_equal 'name default attribute', Person.human_attribute_name('name') assert_equal 'name default attribute', Person.human_attribute_name('name')
end end
def test_translated_model_attributes_using_default_option def test_translated_model_attributes_using_default_option
assert_equal 'name default attribute', Person.human_attribute_name('name', :default => "name default attribute") assert_equal 'name default attribute', Person.human_attribute_name('name', default: "name default attribute")
end end
def test_translated_model_attributes_using_default_option_as_symbol def test_translated_model_attributes_using_default_option_as_symbol
I18n.backend.store_translations 'en', :default_name => 'name default attribute' I18n.backend.store_translations 'en', default_name: 'name default attribute'
assert_equal 'name default attribute', Person.human_attribute_name('name', :default => :default_name) assert_equal 'name default attribute', Person.human_attribute_name('name', default: :default_name)
end end
def test_translated_model_attributes_falling_back_to_default def test_translated_model_attributes_falling_back_to_default
@ -31,71 +31,74 @@ class ActiveModelI18nTests < ActiveModel::TestCase
end end
def test_translated_model_attributes_using_default_option_as_symbol_and_falling_back_to_default 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) assert_equal 'Name', Person.human_attribute_name('name', default: :default_name)
end end
def test_translated_model_attributes_with_symbols def test_translated_model_attributes_with_symbols
I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } } I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute'} } }
assert_equal 'person name attribute', Person.human_attribute_name(:name) assert_equal 'person name attribute', Person.human_attribute_name(:name)
end end
def test_translated_model_attributes_with_ancestor def test_translated_model_attributes_with_ancestor
I18n.backend.store_translations 'en', :activemodel => {:attributes => {:child => {:name => 'child name attribute'} } } I18n.backend.store_translations 'en', activemodel: { attributes: { child: { name: 'child name attribute'} } }
assert_equal 'child name attribute', Child.human_attribute_name('name') assert_equal 'child name attribute', Child.human_attribute_name('name')
end end
def test_translated_model_attributes_with_ancestors_fallback def test_translated_model_attributes_with_ancestors_fallback
I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } } I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute'} } }
assert_equal 'person name attribute', Child.human_attribute_name('name') assert_equal 'person name attribute', Child.human_attribute_name('name')
end end
def test_translated_model_attributes_with_attribute_matching_namespaced_model_name 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'}}} 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', Person.human_attribute_name('gender')
assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute') assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute')
end end
def test_translated_deeply_nested_model_attributes def test_translated_deeply_nested_model_attributes
I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/contacts/addresses" => {:street => 'Deeply Nested Address Street'}}} 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') assert_equal 'Deeply Nested Address Street', Person.human_attribute_name('contacts.addresses.street')
end end
def test_translated_nested_model_attributes def test_translated_nested_model_attributes
I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/addresses" => {:street => 'Person Address Street'}}} I18n.backend.store_translations 'en', activemodel: { attributes: { :"person/addresses" => { street: 'Person Address Street' } } }
assert_equal 'Person Address Street', Person.human_attribute_name('addresses.street') assert_equal 'Person Address Street', Person.human_attribute_name('addresses.street')
end end
def test_translated_nested_model_attributes_with_namespace_fallback def test_translated_nested_model_attributes_with_namespace_fallback
I18n.backend.store_translations 'en', :activemodel => {:attributes => {:addresses => {:street => 'Cool Address Street'}}} I18n.backend.store_translations 'en', activemodel: { attributes: { addresses: { street: 'Cool Address Street' } } }
assert_equal 'Cool Address Street', Person.human_attribute_name('addresses.street') assert_equal 'Cool Address Street', Person.human_attribute_name('addresses.street')
end end
def test_translated_model_names def test_translated_model_names
I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} } I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
assert_equal 'person model', Person.model_name.human assert_equal 'person model', Person.model_name.human
end end
def test_translated_model_names_with_sti def test_translated_model_names_with_sti
I18n.backend.store_translations 'en', :activemodel => {:models => {:child => 'child model'} } I18n.backend.store_translations 'en', activemodel: { models: { child: 'child model' } }
assert_equal 'child model', Child.model_name.human assert_equal 'child model', Child.model_name.human
end end
def test_translated_model_names_with_ancestors_fallback def test_translated_model_names_with_ancestors_fallback
I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} } I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
assert_equal 'person model', Child.model_name.human assert_equal 'person model', Child.model_name.human
end end
def test_human_does_not_modify_options def test_human_does_not_modify_options
options = { :default => 'person model' } options = { default: 'person model' }
Person.model_name.human(options) Person.model_name.human(options)
assert_equal({ :default => 'person model' }, options) assert_equal({ default: 'person model' }, options)
end end
def test_human_attribute_name_does_not_modify_options def test_human_attribute_name_does_not_modify_options
options = { :default => 'Cool gender' } options = { default: 'Cool gender' }
Person.human_attribute_name('gender', options) Person.human_attribute_name('gender', options)
assert_equal({ :default => 'Cool gender' }, options) assert_equal({ default: 'Cool gender' }, options)
end end
end end

View file

@ -30,7 +30,7 @@ class AcceptanceValidationTest < ActiveModel::TestCase
end end
def test_eula def test_eula
Topic.validates_acceptance_of(:eula, :message => "must be abided") Topic.validates_acceptance_of(:eula, message: "must be abided")
t = Topic.new("title" => "We should be confirmed","eula" => "") t = Topic.new("title" => "We should be confirmed","eula" => "")
assert t.invalid? assert t.invalid?
@ -41,7 +41,7 @@ class AcceptanceValidationTest < ActiveModel::TestCase
end end
def test_terms_of_service_agreement_with_accept_value def test_terms_of_service_agreement_with_accept_value
Topic.validates_acceptance_of(:terms_of_service, :accept => "I agree.") Topic.validates_acceptance_of(:terms_of_service, accept: "I agree.")
t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "") t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
assert t.invalid? assert t.invalid?

View file

@ -11,7 +11,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_if_validation_using_method_true def test_if_validation_using_method_true
# When the method returns true # When the method returns true
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => :condition_is_true ) Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true)
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.invalid? assert t.invalid?
assert t.errors[:title].any? assert t.errors[:title].any?
@ -20,7 +20,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_unless_validation_using_method_true def test_unless_validation_using_method_true
# When the method returns true # When the method returns true
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => :condition_is_true ) Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: :condition_is_true)
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.valid? assert t.valid?
assert t.errors[:title].empty? assert t.errors[:title].empty?
@ -28,7 +28,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_if_validation_using_method_false def test_if_validation_using_method_false
# When the method returns false # When the method returns false
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => :condition_is_true_but_its_not ) 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") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.valid? assert t.valid?
assert t.errors[:title].empty? assert t.errors[:title].empty?
@ -36,7 +36,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_unless_validation_using_method_false def test_unless_validation_using_method_false
# When the method returns false # When the method returns false
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => :condition_is_true_but_its_not ) 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") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.invalid? assert t.invalid?
assert t.errors[:title].any? assert t.errors[:title].any?
@ -45,7 +45,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_if_validation_using_string_true def test_if_validation_using_string_true
# When the evaluated string returns true # When the evaluated string returns true
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => "a = 1; a == 1" ) Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: "a = 1; a == 1")
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.invalid? assert t.invalid?
assert t.errors[:title].any? assert t.errors[:title].any?
@ -54,7 +54,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_unless_validation_using_string_true def test_unless_validation_using_string_true
# When the evaluated string returns true # When the evaluated string returns true
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => "a = 1; a == 1" ) Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: "a = 1; a == 1")
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.valid? assert t.valid?
assert t.errors[:title].empty? assert t.errors[:title].empty?
@ -62,7 +62,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_if_validation_using_string_false def test_if_validation_using_string_false
# When the evaluated string returns false # When the evaluated string returns false
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => "false") Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: "false")
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.valid? assert t.valid?
assert t.errors[:title].empty? assert t.errors[:title].empty?
@ -70,7 +70,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_unless_validation_using_string_false def test_unless_validation_using_string_false
# When the evaluated string returns false # When the evaluated string returns false
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => "false") Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: "false")
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.invalid? assert t.invalid?
assert t.errors[:title].any? assert t.errors[:title].any?
@ -79,8 +79,8 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_if_validation_using_block_true def test_if_validation_using_block_true
# When the block returns true # When the block returns true
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
:if => Proc.new { |r| r.content.size > 4 } ) if: Proc.new { |r| r.content.size > 4 })
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.invalid? assert t.invalid?
assert t.errors[:title].any? assert t.errors[:title].any?
@ -89,8 +89,8 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_unless_validation_using_block_true def test_unless_validation_using_block_true
# When the block returns true # When the block returns true
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
:unless => Proc.new { |r| r.content.size > 4 } ) unless: Proc.new { |r| r.content.size > 4 })
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.valid? assert t.valid?
assert t.errors[:title].empty? assert t.errors[:title].empty?
@ -98,8 +98,8 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_if_validation_using_block_false def test_if_validation_using_block_false
# When the block returns false # When the block returns false
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
:if => Proc.new { |r| r.title != "uhohuhoh"} ) if: Proc.new { |r| r.title != "uhohuhoh"})
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.valid? assert t.valid?
assert t.errors[:title].empty? assert t.errors[:title].empty?
@ -107,8 +107,8 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_unless_validation_using_block_false def test_unless_validation_using_block_false
# When the block returns false # When the block returns false
Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
:unless => Proc.new { |r| r.title != "uhohuhoh"} ) unless: Proc.new { |r| r.title != "uhohuhoh"} )
t = Topic.new("title" => "uhohuhoh", "content" => "whatever") t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.invalid? assert t.invalid?
assert t.errors[:title].any? assert t.errors[:title].any?
@ -120,7 +120,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
# ensure that it works correctly # ensure that it works correctly
def test_validation_with_if_as_string def test_validation_with_if_as_string
Topic.validates_presence_of(:title) Topic.validates_presence_of(:title)
Topic.validates_presence_of(:author_name, :if => "title.to_s.match('important')") Topic.validates_presence_of(:author_name, if: "title.to_s.match('important')")
t = Topic.new t = Topic.new
assert t.invalid?, "A topic without a title should not be valid" assert t.invalid?, "A topic without a title should not be valid"

View file

@ -13,7 +13,7 @@ class ConfirmationValidationTest < ActiveModel::TestCase
def test_no_title_confirmation def test_no_title_confirmation
Topic.validates_confirmation_of(:title) Topic.validates_confirmation_of(:title)
t = Topic.new(:author_name => "Plutarch") t = Topic.new(author_name: "Plutarch")
assert t.valid? assert t.valid?
t.title_confirmation = "Parallel Lives" t.title_confirmation = "Parallel Lives"
@ -57,8 +57,8 @@ class ConfirmationValidationTest < ActiveModel::TestCase
I18n.load_path.clear I18n.load_path.clear
I18n.backend = I18n::Backend::Simple.new I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations('en', { I18n.backend.store_translations('en', {
:errors => {:messages => {:confirmation => "doesn't match %{attribute}"}}, errors: { messages: { confirmation: "doesn't match %{attribute}" } },
:activemodel => {:attributes => {:topic => {:title => 'Test Title'}}} activemodel: { attributes: { topic: { title: 'Test Title'} } }
}) })
Topic.validates_confirmation_of(:title) Topic.validates_confirmation_of(:title)

View file

@ -11,14 +11,14 @@ class ExclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_exclusion_of def test_validates_exclusion_of
Topic.validates_exclusion_of( :title, :in => %w( abe monkey ) ) Topic.validates_exclusion_of(:title, in: %w( abe monkey ))
assert Topic.new("title" => "something", "content" => "abc").valid? assert Topic.new("title" => "something", "content" => "abc").valid?
assert Topic.new("title" => "monkey", "content" => "abc").invalid? assert Topic.new("title" => "monkey", "content" => "abc").invalid?
end end
def test_validates_exclusion_of_with_formatted_message def test_validates_exclusion_of_with_formatted_message
Topic.validates_exclusion_of( :title, :in => %w( abe monkey ), :message => "option %{value} is restricted" ) Topic.validates_exclusion_of(:title, in: %w( abe monkey ), message: "option %{value} is restricted")
assert Topic.new("title" => "something", "content" => "abc") assert Topic.new("title" => "something", "content" => "abc")
@ -29,7 +29,7 @@ class ExclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_exclusion_of_with_within_option def test_validates_exclusion_of_with_within_option
Topic.validates_exclusion_of( :title, :within => %w( abe monkey ) ) Topic.validates_exclusion_of(:title, within: %w( abe monkey ))
assert Topic.new("title" => "something", "content" => "abc") assert Topic.new("title" => "something", "content" => "abc")
@ -39,7 +39,7 @@ class ExclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_exclusion_of_for_ruby_class def test_validates_exclusion_of_for_ruby_class
Person.validates_exclusion_of :karma, :in => %w( abe monkey ) Person.validates_exclusion_of :karma, in: %w( abe monkey )
p = Person.new p = Person.new
p.karma = "abe" p.karma = "abe"
@ -54,7 +54,7 @@ class ExclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_exclusion_of_with_lambda 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 ) } Topic.validates_exclusion_of :title, in: lambda { |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
t = Topic.new t = Topic.new
t.title = "elephant" t.title = "elephant"
@ -66,7 +66,7 @@ class ExclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of_with_symbol def test_validates_inclusion_of_with_symbol
Person.validates_exclusion_of :karma, :in => :reserved_karmas Person.validates_exclusion_of :karma, in: :reserved_karmas
p = Person.new p = Person.new
p.karma = "abe" p.karma = "abe"

View file

@ -11,7 +11,7 @@ class PresenceValidationTest < ActiveModel::TestCase
end end
def test_validate_format def test_validate_format
Topic.validates_format_of(:title, :content, :with => /\AValidation\smacros \w+!\z/, :message => "is bad data") 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!") t = Topic.new("title" => "i'm incorrect", "content" => "Validation macros rule!")
assert t.invalid?, "Shouldn't be valid" assert t.invalid?, "Shouldn't be valid"
@ -27,7 +27,7 @@ class PresenceValidationTest < ActiveModel::TestCase
end end
def test_validate_format_with_allow_blank def test_validate_format_with_allow_blank
Topic.validates_format_of(:title, :with => /\AValidation\smacros \w+!\z/, :allow_blank => true) 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" => "Shouldn't be valid").invalid?
assert Topic.new("title" => "").valid? assert Topic.new("title" => "").valid?
assert Topic.new("title" => nil).valid? assert Topic.new("title" => nil).valid?
@ -36,7 +36,7 @@ class PresenceValidationTest < ActiveModel::TestCase
# testing ticket #3142 # testing ticket #3142
def test_validate_format_numeric def test_validate_format_numeric
Topic.validates_format_of(:title, :content, :with => /\A[1-9][0-9]*\z/, :message => "is bad data") Topic.validates_format_of(:title, :content, with: /\A[1-9][0-9]*\z/, message: "is bad data")
t = Topic.new("title" => "72x", "content" => "6789") t = Topic.new("title" => "72x", "content" => "6789")
assert t.invalid?, "Shouldn't be valid" assert t.invalid?, "Shouldn't be valid"
@ -63,24 +63,24 @@ class PresenceValidationTest < ActiveModel::TestCase
end end
def test_validate_format_with_formatted_message def test_validate_format_with_formatted_message
Topic.validates_format_of(:title, :with => /\AValid Title\z/, :message => "can't be %{value}") Topic.validates_format_of(:title, with: /\AValid Title\z/, message: "can't be %{value}")
t = Topic.new(:title => 'Invalid title') t = Topic.new(title: 'Invalid title')
assert t.invalid? assert t.invalid?
assert_equal ["can't be Invalid title"], t.errors[:title] assert_equal ["can't be Invalid title"], t.errors[:title]
end end
def test_validate_format_of_with_multiline_regexp_should_raise_error def test_validate_format_of_with_multiline_regexp_should_raise_error
assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => /^Valid Title$/) } assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: /^Valid Title$/) }
end end
def test_validate_format_of_with_multiline_regexp_and_option def test_validate_format_of_with_multiline_regexp_and_option
assert_nothing_raised(ArgumentError) do assert_nothing_raised(ArgumentError) do
Topic.validates_format_of(:title, :with => /^Valid Title$/, :multiline => true) Topic.validates_format_of(:title, with: /^Valid Title$/, multiline: true)
end end
end end
def test_validate_format_with_not_option def test_validate_format_with_not_option
Topic.validates_format_of(:title, :without => /foo/, :message => "should not contain foo") Topic.validates_format_of(:title, without: /foo/, message: "should not contain foo")
t = Topic.new t = Topic.new
t.title = "foobar" t.title = "foobar"
@ -97,19 +97,19 @@ class PresenceValidationTest < ActiveModel::TestCase
end end
def test_validates_format_of_with_both_regexps_should_raise_error def test_validates_format_of_with_both_regexps_should_raise_error
assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => /this/, :without => /that/) } assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: /this/, without: /that/) }
end end
def test_validates_format_of_when_with_isnt_a_regexp_should_raise_error 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") } assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: "clearly not a regexp") }
end end
def test_validates_format_of_when_not_isnt_a_regexp_should_raise_error 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") } assert_raise(ArgumentError) { Topic.validates_format_of(:title, without: "clearly not a regexp") }
end end
def test_validates_format_of_with_lambda def test_validates_format_of_with_lambda
Topic.validates_format_of :content, :with => lambda{ |topic| topic.title == "digit" ? /\A\d+\Z/ : /\A\S+\Z/ } Topic.validates_format_of :content, with: lambda { |topic| topic.title == "digit" ? /\A\d+\Z/ : /\A\S+\Z/ }
t = Topic.new t = Topic.new
t.title = "digit" t.title = "digit"
@ -121,7 +121,7 @@ class PresenceValidationTest < ActiveModel::TestCase
end end
def test_validates_format_of_without_lambda def test_validates_format_of_without_lambda
Topic.validates_format_of :content, :without => lambda{ |topic| topic.title == "characters" ? /\A\d+\Z/ : /\A\S+\Z/ } Topic.validates_format_of :content, without: lambda { |topic| topic.title == "characters" ? /\A\d+\Z/ : /\A\S+\Z/ }
t = Topic.new t = Topic.new
t.title = "characters" t.title = "characters"
@ -133,7 +133,7 @@ class PresenceValidationTest < ActiveModel::TestCase
end end
def test_validates_format_of_for_ruby_class def test_validates_format_of_for_ruby_class
Person.validates_format_of :karma, :with => /\A\d+\Z/ Person.validates_format_of :karma, with: /\A\d+\Z/
p = Person.new p = Person.new
p.karma = "Pixies" p.karma = "Pixies"

View file

@ -10,29 +10,29 @@ class I18nGenerateMessageValidationTest < ActiveModel::TestCase
# validates_inclusion_of: generate_message(attr_name, :inclusion, message: custom_message, value: value) # validates_inclusion_of: generate_message(attr_name, :inclusion, message: custom_message, value: value)
def test_generate_message_inclusion_with_default_message def test_generate_message_inclusion_with_default_message
assert_equal 'is not included in the list', @person.errors.generate_message(:title, :inclusion, :value => 'title') assert_equal 'is not included in the list', @person.errors.generate_message(:title, :inclusion, value: 'title')
end end
def test_generate_message_inclusion_with_custom_message 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') assert_equal 'custom message title', @person.errors.generate_message(:title, :inclusion, message: 'custom message %{value}', value: 'title')
end end
# validates_exclusion_of: generate_message(attr_name, :exclusion, message: custom_message, value: value) # validates_exclusion_of: generate_message(attr_name, :exclusion, message: custom_message, value: value)
def test_generate_message_exclusion_with_default_message def test_generate_message_exclusion_with_default_message
assert_equal 'is reserved', @person.errors.generate_message(:title, :exclusion, :value => 'title') assert_equal 'is reserved', @person.errors.generate_message(:title, :exclusion, value: 'title')
end end
def test_generate_message_exclusion_with_custom_message 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') assert_equal 'custom message title', @person.errors.generate_message(:title, :exclusion, message: 'custom message %{value}', value: 'title')
end end
# validates_format_of: generate_message(attr_name, :invalid, message: custom_message, value: value) # validates_format_of: generate_message(attr_name, :invalid, message: custom_message, value: value)
def test_generate_message_invalid_with_default_message def test_generate_message_invalid_with_default_message
assert_equal 'is invalid', @person.errors.generate_message(:title, :invalid, :value => 'title') assert_equal 'is invalid', @person.errors.generate_message(:title, :invalid, value: 'title')
end end
def test_generate_message_invalid_with_custom_message 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') assert_equal 'custom message title', @person.errors.generate_message(:title, :invalid, message: 'custom message %{value}', value: 'title')
end end
# validates_confirmation_of: generate_message(attr_name, :confirmation, message: custom_message) # validates_confirmation_of: generate_message(attr_name, :confirmation, message: custom_message)
@ -41,7 +41,7 @@ class I18nGenerateMessageValidationTest < ActiveModel::TestCase
end end
def test_generate_message_confirmation_with_custom_message def test_generate_message_confirmation_with_custom_message
assert_equal 'custom message', @person.errors.generate_message(:title, :confirmation, :message => 'custom message') assert_equal 'custom message', @person.errors.generate_message(:title, :confirmation, message: 'custom message')
end end
# validates_acceptance_of: generate_message(attr_name, :accepted, message: custom_message) # validates_acceptance_of: generate_message(attr_name, :accepted, message: custom_message)
@ -50,7 +50,7 @@ class I18nGenerateMessageValidationTest < ActiveModel::TestCase
end end
def test_generate_message_accepted_with_custom_message def test_generate_message_accepted_with_custom_message
assert_equal 'custom message', @person.errors.generate_message(:title, :accepted, :message => 'custom message') assert_equal 'custom message', @person.errors.generate_message(:title, :accepted, message: 'custom message')
end end
# add_on_empty: generate_message(attr, :empty, message: custom_message) # add_on_empty: generate_message(attr, :empty, message: custom_message)
@ -59,7 +59,7 @@ class I18nGenerateMessageValidationTest < ActiveModel::TestCase
end end
def test_generate_message_empty_with_custom_message def test_generate_message_empty_with_custom_message
assert_equal 'custom message', @person.errors.generate_message(:title, :empty, :message => 'custom message') assert_equal 'custom message', @person.errors.generate_message(:title, :empty, message: 'custom message')
end end
# add_on_blank: generate_message(attr, :blank, message: custom_message) # add_on_blank: generate_message(attr, :blank, message: custom_message)
@ -68,71 +68,71 @@ class I18nGenerateMessageValidationTest < ActiveModel::TestCase
end end
def test_generate_message_blank_with_custom_message def test_generate_message_blank_with_custom_message
assert_equal 'custom message', @person.errors.generate_message(:title, :blank, :message => 'custom message') assert_equal 'custom message', @person.errors.generate_message(:title, :blank, message: 'custom message')
end end
# validates_length_of: generate_message(attr, :too_long, message: custom_message, count: option_value.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 def test_generate_message_too_long_with_default_message
assert_equal "is too long (maximum is 10 characters)", @person.errors.generate_message(:title, :too_long, :count => 10) assert_equal "is too long (maximum is 10 characters)", @person.errors.generate_message(:title, :too_long, count: 10)
end end
def test_generate_message_too_long_with_custom_message 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) assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_long, message: 'custom message %{count}', count: 10)
end end
# validates_length_of: generate_message(attr, :too_short, default: custom_message, count: option_value.begin) # validates_length_of: generate_message(attr, :too_short, default: custom_message, count: option_value.begin)
def test_generate_message_too_short_with_default_message def test_generate_message_too_short_with_default_message
assert_equal "is too short (minimum is 10 characters)", @person.errors.generate_message(:title, :too_short, :count => 10) assert_equal "is too short (minimum is 10 characters)", @person.errors.generate_message(:title, :too_short, count: 10)
end end
def test_generate_message_too_short_with_custom_message 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) assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_short, message: 'custom message %{count}', count: 10)
end end
# validates_length_of: generate_message(attr, :wrong_length, message: custom_message, count: option_value) # validates_length_of: generate_message(attr, :wrong_length, message: custom_message, count: option_value)
def test_generate_message_wrong_length_with_default_message def test_generate_message_wrong_length_with_default_message
assert_equal "is the wrong length (should be 10 characters)", @person.errors.generate_message(:title, :wrong_length, :count => 10) assert_equal "is the wrong length (should be 10 characters)", @person.errors.generate_message(:title, :wrong_length, count: 10)
end end
def test_generate_message_wrong_length_with_custom_message 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) assert_equal 'custom message 10', @person.errors.generate_message(:title, :wrong_length, message: 'custom message %{count}', count: 10)
end end
# validates_numericality_of: generate_message(attr_name, :not_a_number, value: raw_value, message: custom_message) # 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 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') assert_equal "is not a number", @person.errors.generate_message(:title, :not_a_number, value: 'title')
end end
def test_generate_message_not_a_number_with_custom_message 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') assert_equal 'custom message title', @person.errors.generate_message(:title, :not_a_number, message: 'custom message %{value}', value: 'title')
end end
# validates_numericality_of: generate_message(attr_name, option, value: raw_value, default: custom_message) # validates_numericality_of: generate_message(attr_name, option, value: raw_value, default: custom_message)
def test_generate_message_greater_than_with_default_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) assert_equal "must be greater than 10", @person.errors.generate_message(:title, :greater_than, value: 'title', count: 10)
end end
def test_generate_message_greater_than_or_equal_to_with_default_message 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) 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 end
def test_generate_message_equal_to_with_default_message 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) assert_equal "must be equal to 10", @person.errors.generate_message(:title, :equal_to, value: 'title', count: 10)
end end
def test_generate_message_less_than_with_default_message 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) assert_equal "must be less than 10", @person.errors.generate_message(:title, :less_than, value: 'title', count: 10)
end end
def test_generate_message_less_than_or_equal_to_with_default_message 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) 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 end
def test_generate_message_odd_with_default_message def test_generate_message_odd_with_default_message
assert_equal "must be odd", @person.errors.generate_message(:title, :odd, :value => 'title', :count => 10) assert_equal "must be odd", @person.errors.generate_message(:title, :odd, value: 'title', count: 10)
end end
def test_generate_message_even_with_default_message def test_generate_message_even_with_default_message
assert_equal "must be even", @person.errors.generate_message(:title, :even, :value => 'title', :count => 10) assert_equal "must be even", @person.errors.generate_message(:title, :even, value: 'title', count: 10)
end end
end end

View file

@ -12,7 +12,7 @@ class I18nValidationTest < ActiveModel::TestCase
@old_load_path, @old_backend = I18n.load_path.dup, I18n.backend @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
I18n.load_path.clear I18n.load_path.clear
I18n.backend = I18n::Backend::Simple.new I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations('en', :errors => {:messages => {:custom => nil}}) I18n.backend.store_translations('en', errors: { messages: { custom: nil } })
end end
def teardown def teardown
@ -22,21 +22,21 @@ class I18nValidationTest < ActiveModel::TestCase
end end
def test_full_message_encoding def test_full_message_encoding
I18n.backend.store_translations('en', :errors => { I18n.backend.store_translations('en', errors: {
:messages => { :too_short => '猫舌' }}) messages: { too_short: '猫舌' } })
Person.validates_length_of :title, :within => 3..5 Person.validates_length_of :title, within: 3..5
@person.valid? @person.valid?
assert_equal ['Title 猫舌'], @person.errors.full_messages assert_equal ['Title 猫舌'], @person.errors.full_messages
end end
def test_errors_full_messages_translates_human_attribute_name_for_model_attributes def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
@person.errors.add(:name, 'not found') @person.errors.add(:name, 'not found')
Person.expects(:human_attribute_name).with(:name, :default => 'Name').returns("Person's name") Person.expects(:human_attribute_name).with(:name, default: 'Name').returns("Person's name")
assert_equal ["Person's name not found"], @person.errors.full_messages assert_equal ["Person's name not found"], @person.errors.full_messages
end end
def test_errors_full_messages_uses_format def test_errors_full_messages_uses_format
I18n.backend.store_translations('en', :errors => {:format => "Field %{attribute} %{message}"}) I18n.backend.store_translations('en', errors: { format: "Field %{attribute} %{message}" })
@person.errors.add('name', 'empty') @person.errors.add('name', 'empty')
assert_equal ["Field Name empty"], @person.errors.full_messages assert_equal ["Field Name empty"], @person.errors.full_messages
end end
@ -49,10 +49,10 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES = [ COMMON_CASES = [
# [ case, validation_options, generate_message_options] # [ case, validation_options, generate_message_options]
[ "given no options", {}, {}], [ "given no options", {}, {}],
[ "given custom message", {:message => "custom"}, {:message => "custom"}], [ "given custom message", { message: "custom" }, { message: "custom" }],
[ "given if condition", {:if => lambda { true }}, {}], [ "given if condition", { if: lambda { true }}, {}],
[ "given unless condition", {:unless => lambda { false }}, {}], [ "given unless condition", { unless: lambda { false }}, {}],
[ "given option that is not reserved", {:format => "jpg"}, {:format => "jpg" }] [ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }]
] ]
# validates_confirmation_of w/ mocha # validates_confirmation_of w/ mocha
@ -61,7 +61,7 @@ class I18nValidationTest < ActiveModel::TestCase
test "validates_confirmation_of on generated message #{name}" do test "validates_confirmation_of on generated message #{name}" do
Person.validates_confirmation_of :title, validation_options Person.validates_confirmation_of :title, validation_options
@person.title_confirmation = 'foo' @person.title_confirmation = 'foo'
@person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(:attribute => 'Title')) @person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title'))
@person.valid? @person.valid?
end end
end end
@ -70,7 +70,7 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_acceptance_of on generated message #{name}" do test "validates_acceptance_of on generated message #{name}" do
Person.validates_acceptance_of :title, validation_options.merge(:allow_nil => false) Person.validates_acceptance_of :title, validation_options.merge(allow_nil: false)
@person.errors.expects(:generate_message).with(:title, :accepted, generate_message_options) @person.errors.expects(:generate_message).with(:title, :accepted, generate_message_options)
@person.valid? @person.valid?
end end
@ -90,8 +90,8 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :withing on generated message when too short #{name}" do 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.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.errors.expects(:generate_message).with(:title, :too_short, generate_message_options.merge(count: 3))
@person.valid? @person.valid?
end end
end end
@ -100,9 +100,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :too_long generated message #{name}" do test "validates_length_of for :too_long generated message #{name}" do
Person.validates_length_of :title, validation_options.merge(:within => 3..5) Person.validates_length_of :title, validation_options.merge(within: 3..5)
@person.title = 'this title is too long' @person.title = 'this title is too long'
@person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(:count => 5)) @person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(count: 5))
@person.valid? @person.valid?
end end
end end
@ -111,8 +111,8 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :is on generated message #{name}" do test "validates_length_of for :is on generated message #{name}" do
Person.validates_length_of :title, validation_options.merge(:is => 5) 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.errors.expects(:generate_message).with(:title, :wrong_length, generate_message_options.merge(count: 5))
@person.valid? @person.valid?
end end
end end
@ -121,9 +121,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_format_of on generated message #{name}" do 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.validates_format_of :title, validation_options.merge(with: /\A[1-9][0-9]*\z/)
@person.title = '72x' @person.title = '72x'
@person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(:value => '72x')) @person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(value: '72x'))
@person.valid? @person.valid?
end end
end end
@ -132,9 +132,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_inclusion_of on generated message #{name}" do test "validates_inclusion_of on generated message #{name}" do
Person.validates_inclusion_of :title, validation_options.merge(:in => %w(a b c)) Person.validates_inclusion_of :title, validation_options.merge(in: %w(a b c))
@person.title = 'z' @person.title = 'z'
@person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(:value => 'z')) @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
@person.valid? @person.valid?
end end
end end
@ -143,9 +143,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_inclusion_of using :within on generated message #{name}" do 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.validates_inclusion_of :title, validation_options.merge(within: %w(a b c))
@person.title = 'z' @person.title = 'z'
@person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(:value => 'z')) @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
@person.valid? @person.valid?
end end
end end
@ -154,9 +154,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_exclusion_of generated message #{name}" do test "validates_exclusion_of generated message #{name}" do
Person.validates_exclusion_of :title, validation_options.merge(:in => %w(a b c)) Person.validates_exclusion_of :title, validation_options.merge(in: %w(a b c))
@person.title = 'a' @person.title = 'a'
@person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(:value => 'a')) @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
@person.valid? @person.valid?
end end
end end
@ -165,9 +165,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_exclusion_of using :within generated message #{name}" do test "validates_exclusion_of using :within generated message #{name}" do
Person.validates_exclusion_of :title, validation_options.merge(:within => %w(a b c)) Person.validates_exclusion_of :title, validation_options.merge(within: %w(a b c))
@person.title = 'a' @person.title = 'a'
@person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(:value => 'a')) @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
@person.valid? @person.valid?
end end
end end
@ -178,7 +178,7 @@ class I18nValidationTest < ActiveModel::TestCase
test "validates_numericality_of generated message #{name}" do test "validates_numericality_of generated message #{name}" do
Person.validates_numericality_of :title, validation_options Person.validates_numericality_of :title, validation_options
@person.title = 'a' @person.title = 'a'
@person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(:value => 'a')) @person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(value: 'a'))
@person.valid? @person.valid?
end end
end end
@ -187,9 +187,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :only_integer on generated message #{name}" do test "validates_numericality_of for :only_integer on generated message #{name}" do
Person.validates_numericality_of :title, validation_options.merge(:only_integer => true) Person.validates_numericality_of :title, validation_options.merge(only_integer: true)
@person.title = '0.0' @person.title = '0.0'
@person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(:value => '0.0')) @person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(value: '0.0'))
@person.valid? @person.valid?
end end
end end
@ -198,9 +198,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :odd on generated message #{name}" do 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.validates_numericality_of :title, validation_options.merge(only_integer: true, odd: true)
@person.title = 0 @person.title = 0
@person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(:value => 0)) @person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(value: 0))
@person.valid? @person.valid?
end end
end end
@ -209,9 +209,9 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options| COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :less_than on generated message #{name}" do 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.validates_numericality_of :title, validation_options.merge(only_integer: true, less_than: 0)
@person.title = 1 @person.title = 1
@person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(:value => 1, :count => 0)) @person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(value: 1, count: 0))
@person.valid? @person.valid?
end end
end end
@ -226,8 +226,8 @@ class I18nValidationTest < ActiveModel::TestCase
end end
# test "validates_confirmation_of finds custom model key translation when blank" # test "validates_confirmation_of finds custom model key translation when blank"
test "#{validation} finds custom model key translation when #{error_type}" do 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', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message' } } } } } }
I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}} I18n.backend.store_translations 'en', errors: { messages: { error_type => 'global message'}}
yield(@person, {}) yield(@person, {})
@person.valid? @person.valid?
@ -236,17 +236,17 @@ class I18nValidationTest < ActiveModel::TestCase
# test "validates_confirmation_of finds custom model key translation with interpolation when blank" # 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 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', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message with %{extra}' } } } } } }
I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}} I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
yield(@person, {:extra => "extra information"}) yield(@person, { extra: "extra information" })
@person.valid? @person.valid?
assert_equal ['custom message with extra information'], @person.errors[attribute] assert_equal ['custom message with extra information'], @person.errors[attribute]
end end
# test "validates_confirmation_of finds global default key translation when blank" # test "validates_confirmation_of finds global default key translation when blank"
test "#{validation} finds global default key translation when #{error_type}" do test "#{validation} finds global default key translation when #{error_type}" do
I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}} I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
yield(@person, {}) yield(@person, {})
@person.valid? @person.valid?
@ -264,7 +264,7 @@ class I18nValidationTest < ActiveModel::TestCase
# validates_acceptance_of w/o mocha # validates_acceptance_of w/o mocha
set_expectations_for_validation "validates_acceptance_of", :accepted do |person, options_to_merge| 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) Person.validates_acceptance_of :title, options_to_merge.merge(allow_nil: false)
end end
# validates_presence_of w/o mocha # validates_presence_of w/o mocha
@ -276,36 +276,36 @@ class I18nValidationTest < ActiveModel::TestCase
# validates_length_of :within w/o mocha # validates_length_of :within w/o mocha
set_expectations_for_validation "validates_length_of", :too_short do |person, options_to_merge| 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) Person.validates_length_of :title, options_to_merge.merge(within: 3..5)
end end
set_expectations_for_validation "validates_length_of", :too_long do |person, options_to_merge| 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.validates_length_of :title, options_to_merge.merge(within: 3..5)
person.title = "too long" person.title = "too long"
end end
# validates_length_of :is w/o mocha # validates_length_of :is w/o mocha
set_expectations_for_validation "validates_length_of", :wrong_length do |person, options_to_merge| 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) Person.validates_length_of :title, options_to_merge.merge(is: 5)
end end
# validates_format_of w/o mocha # validates_format_of w/o mocha
set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge| 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/) Person.validates_format_of :title, options_to_merge.merge(with: /\A[1-9][0-9]*\z/)
end end
# validates_inclusion_of w/o mocha # validates_inclusion_of w/o mocha
set_expectations_for_validation "validates_inclusion_of", :inclusion do |person, options_to_merge| 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)) Person.validates_inclusion_of :title, options_to_merge.merge(in: %w(a b c))
end end
# validates_exclusion_of w/o mocha # validates_exclusion_of w/o mocha
set_expectations_for_validation "validates_exclusion_of", :exclusion do |person, options_to_merge| 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.validates_exclusion_of :title, options_to_merge.merge(in: %w(a b c))
person.title = 'a' person.title = 'a'
end end
@ -319,55 +319,54 @@ class I18nValidationTest < ActiveModel::TestCase
# validates_numericality_of with :only_integer w/o mocha # validates_numericality_of with :only_integer w/o mocha
set_expectations_for_validation "validates_numericality_of", :not_an_integer do |person, options_to_merge| 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.validates_numericality_of :title, options_to_merge.merge(only_integer: true)
person.title = '1.0' person.title = '1.0'
end end
# validates_numericality_of :odd w/o mocha # validates_numericality_of :odd w/o mocha
set_expectations_for_validation "validates_numericality_of", :odd do |person, options_to_merge| 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.validates_numericality_of :title, options_to_merge.merge(only_integer: true, odd: true)
person.title = 0 person.title = 0
end end
# validates_numericality_of :less_than w/o mocha # validates_numericality_of :less_than w/o mocha
set_expectations_for_validation "validates_numericality_of", :less_than do |person, options_to_merge| 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.validates_numericality_of :title, options_to_merge.merge(only_integer: true, less_than: 0)
person.title = 1 person.title = 1
end end
# test with validates_with # test with validates_with
def test_validations_with_message_symbol_must_translate def test_validations_with_message_symbol_must_translate
I18n.backend.store_translations 'en', :errors => {:messages => {:custom_error => "I am a custom error"}} I18n.backend.store_translations 'en', errors: { messages: { custom_error: "I am a custom error" } }
Person.validates_presence_of :title, :message => :custom_error Person.validates_presence_of :title, message: :custom_error
@person.title = nil @person.title = nil
@person.valid? @person.valid?
assert_equal ["I am a custom error"], @person.errors[:title] assert_equal ["I am a custom error"], @person.errors[:title]
end end
def test_validates_with_message_symbol_must_translate_per_attribute 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"}}}}}} 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.validates_presence_of :title, message: :custom_error
@person.title = nil @person.title = nil
@person.valid? @person.valid?
assert_equal ["I am a custom error"], @person.errors[:title] assert_equal ["I am a custom error"], @person.errors[:title]
end end
def test_validates_with_message_symbol_must_translate_per_model 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"}}}} 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.validates_presence_of :title, message: :custom_error
@person.title = nil @person.title = nil
@person.valid? @person.valid?
assert_equal ["I am a custom error"], @person.errors[:title] assert_equal ["I am a custom error"], @person.errors[:title]
end end
def test_validates_with_message_string def test_validates_with_message_string
Person.validates_presence_of :title, :message => "I am a custom error" Person.validates_presence_of :title, message: "I am a custom error"
@person.title = nil @person.title = nil
@person.valid? @person.valid?
assert_equal ["I am a custom error"], @person.errors[:title] assert_equal ["I am a custom error"], @person.errors[:title]
end end
end end

View file

@ -11,7 +11,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of_range def test_validates_inclusion_of_range
Topic.validates_inclusion_of( :title, :in => 'aaa'..'bbb' ) Topic.validates_inclusion_of(:title, in: 'aaa'..'bbb')
assert Topic.new("title" => "bbc", "content" => "abc").invalid? assert Topic.new("title" => "bbc", "content" => "abc").invalid?
assert Topic.new("title" => "aa", "content" => "abc").invalid? assert Topic.new("title" => "aa", "content" => "abc").invalid?
assert Topic.new("title" => "aaa", "content" => "abc").valid? assert Topic.new("title" => "aaa", "content" => "abc").valid?
@ -20,7 +20,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of def test_validates_inclusion_of
Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) ) 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!", "content" => "abc").invalid?
assert Topic.new("title" => "a b", "content" => "abc").invalid? assert Topic.new("title" => "a b", "content" => "abc").invalid?
@ -33,16 +33,16 @@ class InclusionValidationTest < ActiveModel::TestCase
assert t.errors[:title].any? assert t.errors[:title].any?
assert_equal ["is not included in the list"], t.errors[:title] 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: nil) }
assert_raise(ArgumentError) { Topic.validates_inclusion_of( :title, :in => 0) } 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: "hi!") }
assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => {} ) } assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: {}) }
assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => [] ) } assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: []) }
end end
def test_validates_inclusion_of_with_allow_nil 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 ) 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" => "a!", "content" => "abc").invalid?
assert Topic.new("title" => "", "content" => "abc").invalid? assert Topic.new("title" => "", "content" => "abc").invalid?
@ -50,7 +50,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of_with_formatted_message 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" ) 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? assert Topic.new("title" => "a", "content" => "abc").valid?
@ -61,7 +61,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of_with_within_option def test_validates_inclusion_of_with_within_option
Topic.validates_inclusion_of( :title, :within => %w( a b c d e f g ) ) Topic.validates_inclusion_of(:title, within: %w( a b c d e f g ))
assert Topic.new("title" => "a", "content" => "abc").valid? assert Topic.new("title" => "a", "content" => "abc").valid?
@ -71,7 +71,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of_for_ruby_class def test_validates_inclusion_of_for_ruby_class
Person.validates_inclusion_of :karma, :in => %w( abe monkey ) Person.validates_inclusion_of :karma, in: %w( abe monkey )
p = Person.new p = Person.new
p.karma = "Lifo" p.karma = "Lifo"
@ -86,7 +86,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of_with_lambda 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 ) } Topic.validates_inclusion_of :title, in: lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
t = Topic.new t = Topic.new
t.title = "wasabi" t.title = "wasabi"
@ -98,7 +98,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end end
def test_validates_inclusion_of_with_symbol def test_validates_inclusion_of_with_symbol
Person.validates_inclusion_of :karma, :in => :available_karmas Person.validates_inclusion_of :karma, in: :available_karmas
p = Person.new p = Person.new
p.karma = "Lifo" p.karma = "Lifo"

View file

@ -30,84 +30,84 @@ class NumericalityValidationTest < ActiveModel::TestCase
end end
def test_validates_numericality_of_with_nil_allowed def test_validates_numericality_of_with_nil_allowed
Topic.validates_numericality_of :approved, :allow_nil => true Topic.validates_numericality_of :approved, allow_nil: true
invalid!(JUNK + BLANK) invalid!(JUNK + BLANK)
valid!(NIL + FLOATS + INTEGERS + BIGDECIMAL + INFINITY) valid!(NIL + FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
end end
def test_validates_numericality_of_with_integer_only def test_validates_numericality_of_with_integer_only
Topic.validates_numericality_of :approved, :only_integer => true Topic.validates_numericality_of :approved, only_integer: true
invalid!(NIL + BLANK + JUNK + FLOATS + BIGDECIMAL + INFINITY) invalid!(NIL + BLANK + JUNK + FLOATS + BIGDECIMAL + INFINITY)
valid!(INTEGERS) valid!(INTEGERS)
end end
def test_validates_numericality_of_with_integer_only_and_nil_allowed def test_validates_numericality_of_with_integer_only_and_nil_allowed
Topic.validates_numericality_of :approved, :only_integer => true, :allow_nil => true Topic.validates_numericality_of :approved, only_integer: true, allow_nil: true
invalid!(JUNK + BLANK + FLOATS + BIGDECIMAL + INFINITY) invalid!(JUNK + BLANK + FLOATS + BIGDECIMAL + INFINITY)
valid!(NIL + INTEGERS) valid!(NIL + INTEGERS)
end end
def test_validates_numericality_with_greater_than def test_validates_numericality_with_greater_than
Topic.validates_numericality_of :approved, :greater_than => 10 Topic.validates_numericality_of :approved, greater_than: 10
invalid!([-10, 10], 'must be greater than 10') invalid!([-10, 10], 'must be greater than 10')
valid!([11]) valid!([11])
end end
def test_validates_numericality_with_greater_than_or_equal def test_validates_numericality_with_greater_than_or_equal
Topic.validates_numericality_of :approved, :greater_than_or_equal_to => 10 Topic.validates_numericality_of :approved, greater_than_or_equal_to: 10
invalid!([-9, 9], 'must be greater than or equal to 10') invalid!([-9, 9], 'must be greater than or equal to 10')
valid!([10]) valid!([10])
end end
def test_validates_numericality_with_equal_to def test_validates_numericality_with_equal_to
Topic.validates_numericality_of :approved, :equal_to => 10 Topic.validates_numericality_of :approved, equal_to: 10
invalid!([-10, 11] + INFINITY, 'must be equal to 10') invalid!([-10, 11] + INFINITY, 'must be equal to 10')
valid!([10]) valid!([10])
end end
def test_validates_numericality_with_less_than def test_validates_numericality_with_less_than
Topic.validates_numericality_of :approved, :less_than => 10 Topic.validates_numericality_of :approved, less_than: 10
invalid!([10], 'must be less than 10') invalid!([10], 'must be less than 10')
valid!([-9, 9]) valid!([-9, 9])
end end
def test_validates_numericality_with_less_than_or_equal_to def test_validates_numericality_with_less_than_or_equal_to
Topic.validates_numericality_of :approved, :less_than_or_equal_to => 10 Topic.validates_numericality_of :approved, less_than_or_equal_to: 10
invalid!([11], 'must be less than or equal to 10') invalid!([11], 'must be less than or equal to 10')
valid!([-10, 10]) valid!([-10, 10])
end end
def test_validates_numericality_with_odd def test_validates_numericality_with_odd
Topic.validates_numericality_of :approved, :odd => true Topic.validates_numericality_of :approved, odd: true
invalid!([-2, 2], 'must be odd') invalid!([-2, 2], 'must be odd')
valid!([-1, 1]) valid!([-1, 1])
end end
def test_validates_numericality_with_even def test_validates_numericality_with_even
Topic.validates_numericality_of :approved, :even => true Topic.validates_numericality_of :approved, even: true
invalid!([-1, 1], 'must be even') invalid!([-1, 1], 'must be even')
valid!([-2, 2]) valid!([-2, 2])
end end
def test_validates_numericality_with_greater_than_less_than_and_even def test_validates_numericality_with_greater_than_less_than_and_even
Topic.validates_numericality_of :approved, :greater_than => 1, :less_than => 4, :even => true Topic.validates_numericality_of :approved, greater_than: 1, less_than: 4, even: true
invalid!([1, 3, 4]) invalid!([1, 3, 4])
valid!([2]) valid!([2])
end end
def test_validates_numericality_with_other_than def test_validates_numericality_with_other_than
Topic.validates_numericality_of :approved, :other_than => 0 Topic.validates_numericality_of :approved, other_than: 0
invalid!([0, 0.0]) invalid!([0, 0.0])
valid!([-1, 42]) valid!([-1, 42])
@ -115,7 +115,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
def test_validates_numericality_with_proc def test_validates_numericality_with_proc
Topic.send(:define_method, :min_approved, lambda { 5 }) 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 {|topic| topic.min_approved }
invalid!([3, 4]) invalid!([3, 4])
valid!([5, 6]) valid!([5, 6])
@ -124,7 +124,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
def test_validates_numericality_with_symbol def test_validates_numericality_with_symbol
Topic.send(:define_method, :max_approved, lambda { 5 }) Topic.send(:define_method, :max_approved, lambda { 5 })
Topic.validates_numericality_of :approved, :less_than_or_equal_to => :max_approved Topic.validates_numericality_of :approved, less_than_or_equal_to: :max_approved
invalid!([6]) invalid!([6])
valid!([4, 5]) valid!([4, 5])
@ -132,13 +132,13 @@ class NumericalityValidationTest < ActiveModel::TestCase
end end
def test_validates_numericality_with_numeric_message def test_validates_numericality_with_numeric_message
Topic.validates_numericality_of :approved, :less_than => 4, :message => "smaller than %{count}" Topic.validates_numericality_of :approved, less_than: 4, message: "smaller than %{count}"
topic = Topic.new("title" => "numeric test", "approved" => 10) topic = Topic.new("title" => "numeric test", "approved" => 10)
assert !topic.valid? assert !topic.valid?
assert_equal ["smaller than 4"], topic.errors[:approved] assert_equal ["smaller than 4"], topic.errors[:approved]
Topic.validates_numericality_of :approved, :greater_than => 4, :message => "greater than %{count}" Topic.validates_numericality_of :approved, greater_than: 4, message: "greater than %{count}"
topic = Topic.new("title" => "numeric test", "approved" => 1) topic = Topic.new("title" => "numeric test", "approved" => 1)
assert !topic.valid? assert !topic.valid?
@ -146,7 +146,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
end end
def test_validates_numericality_of_for_ruby_class def test_validates_numericality_of_for_ruby_class
Person.validates_numericality_of :karma, :allow_nil => false Person.validates_numericality_of :karma, allow_nil: false
p = Person.new p = Person.new
p.karma = "Pix" p.karma = "Pix"
@ -161,11 +161,11 @@ class NumericalityValidationTest < ActiveModel::TestCase
end end
def test_validates_numericality_with_invalid_args 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, 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, 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, greater_than: "foo" }
assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :less_than => "foo" } assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than: "foo" }
assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :equal_to => "foo" } assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, equal_to: "foo" }
end end
private private
@ -185,7 +185,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
end end
def with_each_topic_approved_value(values) def with_each_topic_approved_value(values)
topic = Topic.new(:title => "numeric test", :content => "whatever") topic = Topic.new(title: "numeric test", content: "whatever")
values.each do |value| values.each do |value|
topic.approved = value topic.approved = value
yield topic, value yield topic, value

View file

@ -17,20 +17,20 @@ class ValidatesTest < ActiveModel::TestCase
end end
def test_validates_with_messages_empty def test_validates_with_messages_empty
Person.validates :title, :presence => {:message => "" } Person.validates :title, presence: { message: "" }
person = Person.new person = Person.new
assert !person.valid?, 'person should not be valid.' assert !person.valid?, 'person should not be valid.'
end end
def test_validates_with_built_in_validation def test_validates_with_built_in_validation
Person.validates :title, :numericality => true Person.validates :title, numericality: true
person = Person.new person = Person.new
person.valid? person.valid?
assert_equal ['is not a number'], person.errors[:title] assert_equal ['is not a number'], person.errors[:title]
end end
def test_validates_with_attribute_specified_as_string def test_validates_with_attribute_specified_as_string
Person.validates "title", :numericality => true Person.validates "title", numericality: true
person = Person.new person = Person.new
person.valid? person.valid?
assert_equal ['is not a number'], person.errors[:title] assert_equal ['is not a number'], person.errors[:title]
@ -41,14 +41,14 @@ class ValidatesTest < ActiveModel::TestCase
end end
def test_validates_with_built_in_validation_and_options def test_validates_with_built_in_validation_and_options
Person.validates :salary, :numericality => { :message => 'my custom message' } Person.validates :salary, numericality: { message: 'my custom message' }
person = Person.new person = Person.new
person.valid? person.valid?
assert_equal ['my custom message'], person.errors[:salary] assert_equal ['my custom message'], person.errors[:salary]
end end
def test_validates_with_validator_class def test_validates_with_validator_class
Person.validates :karma, :email => true Person.validates :karma, email: true
person = Person.new person = Person.new
person.valid? person.valid?
assert_equal ['is not an email'], person.errors[:karma] assert_equal ['is not an email'], person.errors[:karma]
@ -62,33 +62,33 @@ class ValidatesTest < ActiveModel::TestCase
end end
def test_validates_with_if_as_local_conditions def test_validates_with_if_as_local_conditions
Person.validates :karma, :presence => true, :email => { :unless => :condition_is_true } Person.validates :karma, presence: true, email: { unless: :condition_is_true }
person = Person.new person = Person.new
person.valid? person.valid?
assert_equal ["can't be blank"], person.errors[:karma] assert_equal ["can't be blank"], person.errors[:karma]
end end
def test_validates_with_if_as_shared_conditions def test_validates_with_if_as_shared_conditions
Person.validates :karma, :presence => true, :email => true, :if => :condition_is_true Person.validates :karma, presence: true, email: true, if: :condition_is_true
person = Person.new person = Person.new
person.valid? person.valid?
assert_equal ["can't be blank", "is not an email"], person.errors[:karma].sort assert_equal ["can't be blank", "is not an email"], person.errors[:karma].sort
end end
def test_validates_with_unless_shared_conditions def test_validates_with_unless_shared_conditions
Person.validates :karma, :presence => true, :email => true, :unless => :condition_is_true Person.validates :karma, presence: true, email: true, unless: :condition_is_true
person = Person.new person = Person.new
assert person.valid? assert person.valid?
end end
def test_validates_with_allow_nil_shared_conditions def test_validates_with_allow_nil_shared_conditions
Person.validates :karma, :length => { :minimum => 20 }, :email => true, :allow_nil => true Person.validates :karma, length: { minimum: 20 }, email: true, allow_nil: true
person = Person.new person = Person.new
assert person.valid? assert person.valid?
end end
def test_validates_with_regexp def test_validates_with_regexp
Person.validates :karma, :format => /positive|negative/ Person.validates :karma, format: /positive|negative/
person = Person.new person = Person.new
assert person.invalid? assert person.invalid?
assert_equal ['is invalid'], person.errors[:karma] assert_equal ['is invalid'], person.errors[:karma]
@ -97,7 +97,7 @@ class ValidatesTest < ActiveModel::TestCase
end end
def test_validates_with_array def test_validates_with_array
Person.validates :gender, :inclusion => %w(m f) Person.validates :gender, inclusion: %w(m f)
person = Person.new person = Person.new
assert person.invalid? assert person.invalid?
assert_equal ['is not included in the list'], person.errors[:gender] assert_equal ['is not included in the list'], person.errors[:gender]
@ -106,7 +106,7 @@ class ValidatesTest < ActiveModel::TestCase
end end
def test_validates_with_range def test_validates_with_range
Person.validates :karma, :length => 6..20 Person.validates :karma, length: 6..20
person = Person.new person = Person.new
assert person.invalid? assert person.invalid?
assert_equal ['is too short (minimum is 6 characters)'], person.errors[:karma] assert_equal ['is too short (minimum is 6 characters)'], person.errors[:karma]
@ -115,25 +115,25 @@ class ValidatesTest < ActiveModel::TestCase
end end
def test_validates_with_validator_class_and_options def test_validates_with_validator_class_and_options
Person.validates :karma, :email => { :message => 'my custom message' } Person.validates :karma, email: { message: 'my custom message' }
person = Person.new person = Person.new
person.valid? person.valid?
assert_equal ['my custom message'], person.errors[:karma] assert_equal ['my custom message'], person.errors[:karma]
end end
def test_validates_with_unknown_validator def test_validates_with_unknown_validator
assert_raise(ArgumentError) { Person.validates :karma, :unknown => true } assert_raise(ArgumentError) { Person.validates :karma, unknown: true }
end end
def test_validates_with_included_validator def test_validates_with_included_validator
PersonWithValidator.validates :title, :presence => true PersonWithValidator.validates :title, presence: true
person = PersonWithValidator.new person = PersonWithValidator.new
person.valid? person.valid?
assert_equal ['Local validator'], person.errors[:title] assert_equal ['Local validator'], person.errors[:title]
end end
def test_validates_with_included_validator_and_options def test_validates_with_included_validator_and_options
PersonWithValidator.validates :title, :presence => { :custom => ' please' } PersonWithValidator.validates :title, presence: { custom: ' please' }
person = PersonWithValidator.new person = PersonWithValidator.new
person.valid? person.valid?
assert_equal ['Local validator please'], person.errors[:title] assert_equal ['Local validator please'], person.errors[:title]
@ -141,7 +141,7 @@ class ValidatesTest < ActiveModel::TestCase
def test_validates_with_included_validator_and_wildcard_shortcut def test_validates_with_included_validator_and_wildcard_shortcut
# Shortcut for PersonWithValidator.validates :title, like: { with: "Mr." } # Shortcut for PersonWithValidator.validates :title, like: { with: "Mr." }
PersonWithValidator.validates :title, :like => "Mr." PersonWithValidator.validates :title, like: "Mr."
person = PersonWithValidator.new person = PersonWithValidator.new
person.title = "Ms. Pacman" person.title = "Ms. Pacman"
person.valid? person.valid?
@ -149,7 +149,7 @@ class ValidatesTest < ActiveModel::TestCase
end end
def test_defining_extra_default_keys_for_validates def test_defining_extra_default_keys_for_validates
Topic.validates :title, :confirmation => true, :message => 'Y U NO CONFIRM' Topic.validates :title, confirmation: true, message: 'Y U NO CONFIRM'
topic = Topic.new topic = Topic.new
topic.title = "What's happening" topic.title = "What's happening"
topic.title_confirmation = "Not this" topic.title_confirmation = "Not this"

View file

@ -19,21 +19,21 @@ class ValidationsContextTest < ActiveModel::TestCase
end end
test "with a class that adds errors on create and validating a new model with no arguments" do 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.validates_with(ValidatorThatAddsErrors, on: :create)
topic = Topic.new topic = Topic.new
assert topic.valid?, "Validation doesn't run on valid? if 'on' is set to create" assert topic.valid?, "Validation doesn't run on valid? if 'on' is set to create"
end end
test "with a class that adds errors on update and validating a new model" do test "with a class that adds errors on update and validating a new model" do
Topic.validates_with(ValidatorThatAddsErrors, :on => :update) Topic.validates_with(ValidatorThatAddsErrors, on: :update)
topic = Topic.new topic = Topic.new
assert topic.valid?(:create), "Validation doesn't run on create if 'on' is set to update" assert topic.valid?(:create), "Validation doesn't run on create if 'on' is set to update"
end end
test "with a class that adds errors on create and validating a new model" do test "with a class that adds errors on create and validating a new model" do
Topic.validates_with(ValidatorThatAddsErrors, :on => :create) Topic.validates_with(ValidatorThatAddsErrors, on: :create)
topic = Topic.new topic = Topic.new
assert topic.invalid?(:create), "Validation does run on create if 'on' is set to create" assert topic.invalid?(:create), "Validation does run on create if 'on' is set to create"
assert topic.errors[:base].include?(ERROR_MESSAGE) assert topic.errors[:base].include?(ERROR_MESSAGE)
end end
end end

View file

@ -72,26 +72,26 @@ class ValidatesWithTest < ActiveModel::TestCase
end end
test "with if statements that return false" do test "with if statements that return false" do
Topic.validates_with(ValidatorThatAddsErrors, :if => "1 == 2") Topic.validates_with(ValidatorThatAddsErrors, if: "1 == 2")
topic = Topic.new topic = Topic.new
assert topic.valid? assert topic.valid?
end end
test "with if statements that return true" do test "with if statements that return true" do
Topic.validates_with(ValidatorThatAddsErrors, :if => "1 == 1") Topic.validates_with(ValidatorThatAddsErrors, if: "1 == 1")
topic = Topic.new topic = Topic.new
assert topic.invalid? assert topic.invalid?
assert topic.errors[:base].include?(ERROR_MESSAGE) assert topic.errors[:base].include?(ERROR_MESSAGE)
end end
test "with unless statements that return true" do test "with unless statements that return true" do
Topic.validates_with(ValidatorThatAddsErrors, :unless => "1 == 1") Topic.validates_with(ValidatorThatAddsErrors, unless: "1 == 1")
topic = Topic.new topic = Topic.new
assert topic.valid? assert topic.valid?
end end
test "with unless statements that returns false" do test "with unless statements that returns false" do
Topic.validates_with(ValidatorThatAddsErrors, :unless => "1 == 2") Topic.validates_with(ValidatorThatAddsErrors, unless: "1 == 2")
topic = Topic.new topic = Topic.new
assert topic.invalid? assert topic.invalid?
assert topic.errors[:base].include?(ERROR_MESSAGE) assert topic.errors[:base].include?(ERROR_MESSAGE)
@ -100,10 +100,10 @@ class ValidatesWithTest < ActiveModel::TestCase
test "passes all configuration options to the validator class" do test "passes all configuration options to the validator class" do
topic = Topic.new topic = Topic.new
validator = mock() validator = mock()
validator.expects(:new).with(:foo => :bar, :if => "1 == 1").returns(validator) validator.expects(:new).with(foo: :bar, if: "1 == 1").returns(validator)
validator.expects(:validate).with(topic) validator.expects(:validate).with(topic)
Topic.validates_with(validator, :if => "1 == 1", :foo => :bar) Topic.validates_with(validator, if: "1 == 1", foo: :bar)
assert topic.valid? assert topic.valid?
end end
@ -130,15 +130,15 @@ class ValidatesWithTest < ActiveModel::TestCase
end end
test "validates_with with options" do test "validates_with with options" do
Topic.validates_with(ValidatorThatValidatesOptions, :field => :first_name) Topic.validates_with(ValidatorThatValidatesOptions, field: :first_name)
topic = Topic.new topic = Topic.new
assert topic.invalid? assert topic.invalid?
assert topic.errors[:base].include?(ERROR_MESSAGE) assert topic.errors[:base].include?(ERROR_MESSAGE)
end end
test "validates_with each validator" do test "validates_with each validator" do
Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content]) Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content])
topic = Topic.new :title => "Title", :content => "Content" topic = Topic.new title: "Title", content: "Content"
assert topic.invalid? assert topic.invalid?
assert_equal ["Value is Title"], topic.errors[:title] assert_equal ["Value is Title"], topic.errors[:title]
assert_equal ["Value is Content"], topic.errors[:content] assert_equal ["Value is Content"], topic.errors[:content]
@ -146,7 +146,7 @@ class ValidatesWithTest < ActiveModel::TestCase
test "each validator checks validity" do test "each validator checks validity" do
assert_raise RuntimeError do assert_raise RuntimeError do
Topic.validates_with(ValidatorCheckValidity, :attributes => [:title]) Topic.validates_with(ValidatorCheckValidity, attributes: [:title])
end end
end end
@ -157,25 +157,25 @@ class ValidatesWithTest < ActiveModel::TestCase
end end
test "each validator skip nil values if :allow_nil is set to true" do 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.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_nil: true)
topic = Topic.new :content => "" topic = Topic.new content: ""
assert topic.invalid? assert topic.invalid?
assert topic.errors[:title].empty? assert topic.errors[:title].empty?
assert_equal ["Value is "], topic.errors[:content] assert_equal ["Value is "], topic.errors[:content]
end end
test "each validator skip blank values if :allow_blank is set to true" do 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.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_blank: true)
topic = Topic.new :content => "" topic = Topic.new content: ""
assert topic.valid? assert topic.valid?
assert topic.errors[:title].empty? assert topic.errors[:title].empty?
assert topic.errors[:content].empty? assert topic.errors[:content].empty?
end end
test "validates_with can validate with an instance method" do test "validates_with can validate with an instance method" do
Topic.validates :title, :with => :my_validation Topic.validates :title, with: :my_validation
topic = Topic.new :title => "foo" topic = Topic.new title: "foo"
assert topic.valid? assert topic.valid?
assert topic.errors[:title].empty? assert topic.errors[:title].empty?
@ -185,9 +185,9 @@ class ValidatesWithTest < ActiveModel::TestCase
end end
test "optionally pass in the attribute being validated when validating with an instance method" do 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.validates :title, :content, with: :my_validation_with_arg
topic = Topic.new :title => "foo" topic = Topic.new title: "foo"
assert !topic.valid? assert !topic.valid?
assert topic.errors[:title].empty? assert topic.errors[:title].empty?
assert_equal ['is missing'], topic.errors[:content] assert_equal ['is missing'], topic.errors[:content]

View file

@ -190,16 +190,16 @@ class ValidationsTest < ActiveModel::TestCase
def test_validation_order def test_validation_order
Topic.validates_presence_of :title Topic.validates_presence_of :title
Topic.validates_length_of :title, :minimum => 2 Topic.validates_length_of :title, minimum: 2
t = Topic.new("title" => "") t = Topic.new("title" => "")
assert t.invalid? assert t.invalid?
assert_equal "can't be blank", t.errors["title"].first assert_equal "can't be blank", t.errors["title"].first
Topic.validates_presence_of :title, :author_name Topic.validates_presence_of :title, :author_name
Topic.validate {errors.add('author_email_address', 'will never be valid')} Topic.validate {errors.add('author_email_address', 'will never be valid')}
Topic.validates_length_of :title, :content, :minimum => 2 Topic.validates_length_of :title, :content, minimum: 2
t = Topic.new :title => '' t = Topic.new title: ''
assert t.invalid? assert t.invalid?
assert_equal :title, key = t.errors.keys[0] assert_equal :title, key = t.errors.keys[0]
@ -214,9 +214,9 @@ class ValidationsTest < ActiveModel::TestCase
end end
def test_validation_with_if_and_on def test_validation_with_if_and_on
Topic.validates_presence_of :title, :if => Proc.new{|x| x.author_name = "bad"; true }, :on => :update Topic.validates_presence_of :title, if: Proc.new{|x| x.author_name = "bad"; true }, on: :update
t = Topic.new(:title => "") t = Topic.new(title: "")
# If block should not fire # If block should not fire
assert t.valid? assert t.valid?
@ -239,7 +239,7 @@ class ValidationsTest < ActiveModel::TestCase
end end
def test_validation_with_message_as_proc def test_validation_with_message_as_proc
Topic.validates_presence_of(:title, :message => proc { "no blanks here".upcase }) Topic.validates_presence_of(:title, message: proc { "no blanks here".upcase })
t = Topic.new t = Topic.new
assert t.invalid? assert t.invalid?
@ -248,7 +248,7 @@ class ValidationsTest < ActiveModel::TestCase
def test_list_of_validators_for_model def test_list_of_validators_for_model
Topic.validates_presence_of :title Topic.validates_presence_of :title
Topic.validates_length_of :title, :minimum => 2 Topic.validates_length_of :title, minimum: 2
assert_equal 2, Topic.validators.count assert_equal 2, Topic.validators.count
assert_equal [:presence, :length], Topic.validators.map(&:kind) assert_equal [:presence, :length], Topic.validators.map(&:kind)
@ -256,7 +256,7 @@ class ValidationsTest < ActiveModel::TestCase
def test_list_of_validators_on_an_attribute def test_list_of_validators_on_an_attribute
Topic.validates_presence_of :title, :content Topic.validates_presence_of :title, :content
Topic.validates_length_of :title, :minimum => 2 Topic.validates_length_of :title, minimum: 2
assert_equal 2, Topic.validators_on(:title).count assert_equal 2, Topic.validators_on(:title).count
assert_equal [:presence, :length], Topic.validators_on(:title).map(&:kind) assert_equal [:presence, :length], Topic.validators_on(:title).map(&:kind)
@ -265,13 +265,13 @@ class ValidationsTest < ActiveModel::TestCase
end end
def test_accessing_instance_of_validator_on_an_attribute def test_accessing_instance_of_validator_on_an_attribute
Topic.validates_length_of :title, :minimum => 10 Topic.validates_length_of :title, minimum: 10
assert_equal 10, Topic.validators_on(:title).first.options[:minimum] assert_equal 10, Topic.validators_on(:title).first.options[:minimum]
end end
def test_list_of_validators_on_multiple_attributes def test_list_of_validators_on_multiple_attributes
Topic.validates :title, :length => { :minimum => 10 } Topic.validates :title, length: { minimum: 10 }
Topic.validates :author_name, :presence => true, :format => /a/ Topic.validates :author_name, presence: true, format: /a/
validators = Topic.validators_on(:title, :author_name) validators = Topic.validators_on(:title, :author_name)
@ -283,7 +283,7 @@ class ValidationsTest < ActiveModel::TestCase
end end
def test_list_of_validators_will_be_empty_when_empty def test_list_of_validators_will_be_empty_when_empty
Topic.validates :title, :length => { :minimum => 10 } Topic.validates :title, length: { minimum: 10 }
assert_equal [], Topic.validators_on(:author_name) assert_equal [], Topic.validators_on(:author_name)
end end
@ -300,52 +300,52 @@ class ValidationsTest < ActiveModel::TestCase
end end
def test_strict_validation_in_validates def test_strict_validation_in_validates
Topic.validates :title, :strict => true, :presence => true Topic.validates :title, strict: true, presence: true
assert_raises ActiveModel::StrictValidationFailed do assert_raises ActiveModel::StrictValidationFailed do
Topic.new.valid? Topic.new.valid?
end end
end end
def test_strict_validation_not_fails def test_strict_validation_not_fails
Topic.validates :title, :strict => true, :presence => true Topic.validates :title, strict: true, presence: true
assert Topic.new(:title => "hello").valid? assert Topic.new(title: "hello").valid?
end end
def test_strict_validation_particular_validator def test_strict_validation_particular_validator
Topic.validates :title, :presence => { :strict => true } Topic.validates :title, presence: { strict: true }
assert_raises ActiveModel::StrictValidationFailed do assert_raises ActiveModel::StrictValidationFailed do
Topic.new.valid? Topic.new.valid?
end end
end end
def test_strict_validation_in_custom_validator_helper def test_strict_validation_in_custom_validator_helper
Topic.validates_presence_of :title, :strict => true Topic.validates_presence_of :title, strict: true
assert_raises ActiveModel::StrictValidationFailed do assert_raises ActiveModel::StrictValidationFailed do
Topic.new.valid? Topic.new.valid?
end end
end end
def test_strict_validation_custom_exception def test_strict_validation_custom_exception
Topic.validates_presence_of :title, :strict => CustomStrictValidationException Topic.validates_presence_of :title, strict: CustomStrictValidationException
assert_raises CustomStrictValidationException do assert_raises CustomStrictValidationException do
Topic.new.valid? Topic.new.valid?
end end
end end
def test_validates_with_bang def test_validates_with_bang
Topic.validates! :title, :presence => true Topic.validates! :title, presence: true
assert_raises ActiveModel::StrictValidationFailed do assert_raises ActiveModel::StrictValidationFailed do
Topic.new.valid? Topic.new.valid?
end end
end end
def test_validates_with_false_hash_value def test_validates_with_false_hash_value
Topic.validates :title, :presence => false Topic.validates :title, presence: false
assert Topic.new.valid? assert Topic.new.valid?
end end
def test_strict_validation_error_message def test_strict_validation_error_message
Topic.validates :title, :strict => true, :presence => true Topic.validates :title, strict: true, presence: true
exception = assert_raises(ActiveModel::StrictValidationFailed) do exception = assert_raises(ActiveModel::StrictValidationFailed) do
Topic.new.valid? Topic.new.valid?
@ -354,9 +354,9 @@ class ValidationsTest < ActiveModel::TestCase
end end
def test_does_not_modify_options_argument def test_does_not_modify_options_argument
options = { :presence => true } options = { presence: true }
Topic.validates :title, options Topic.validates :title, options
assert_equal({ :presence => true }, options) assert_equal({ presence: true }, options)
end end
def test_dup_validity_is_independent def test_dup_validity_is_independent

View file

@ -7,6 +7,6 @@ class Automobile
def validations def validations
validates_presence_of :make validates_presence_of :make
validates_length_of :model, :within => 2..10 validates_length_of :model, within: 2..10
end end
end end

View file

@ -9,7 +9,7 @@ class Contact
end end
def network def network
{:git => :github} { git: :github }
end end
def initialize(options = {}) def initialize(options = {})

View file

@ -2,11 +2,11 @@ require 'models/topic'
class Reply < Topic class Reply < Topic
validate :errors_on_empty_content validate :errors_on_empty_content
validate :title_is_wrong_create, :on => :create validate :title_is_wrong_create, on: :create
validate :check_empty_title validate :check_empty_title
validate :check_content_mismatch, :on => :create validate :check_content_mismatch, on: :create
validate :check_wrong_update, :on => :update validate :check_wrong_update, on: :update
def check_empty_title def check_empty_title
errors[:title] << "is Empty" unless title && title.size > 0 errors[:title] << "is Empty" unless title && title.size > 0