diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 00000000..91600595 --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1 @@ +service_name: travis-ci diff --git a/.gitignore b/.gitignore index 171f9258..9584ba5e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ pkg/ .rvmrc Gemfile.lock gemfiles/*.lock +.ruby-version +.ruby-gemset +coverage/ diff --git a/.rspec b/.rspec index 42f32465..8c18f1ab 100644 --- a/.rspec +++ b/.rspec @@ -1,2 +1,2 @@ ---format nested +--format documentation --color diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..1e455f2f --- /dev/null +++ b/.travis.yml @@ -0,0 +1,18 @@ +language: ruby +cache: bundler + +services: mongodb + +rvm: + - 1.9.3 + - 2.0.0 + + +script: 'bundle exec rake' + +notifications: + email: + recipients: + - john+timeliness@carney.id.au + on_failure: change + on_success: never diff --git a/Gemfile b/Gemfile index fca88226..f71a6507 100644 --- a/Gemfile +++ b/Gemfile @@ -3,14 +3,12 @@ source 'http://rubygems.org' gemspec gem 'rails', '~> 3.2.6' -gem 'rspec', '~> 2.8' -gem 'rspec-rails', '~> 2.8' gem 'timecop' -gem 'rspec_tag_matchers' gem 'ruby-debug', :platforms => [:ruby_18, :jruby] gem 'debugger', :platforms => [:ruby_19] gem 'appraisal' gem 'sqlite3' +gem 'nokogiri' group :mongoid do gem 'mongoid', '~> 2.3.0' diff --git a/README.md b/README.md new file mode 100644 index 00000000..bada813c --- /dev/null +++ b/README.md @@ -0,0 +1,320 @@ +# ValidatesTimeliness +[![Gem Version][gem-badge]][gem] +[![Build status][build-badge]][build] +[![Coverage Status][coverage-badge]][coverage] + +## Description + +Complete validation of dates, times and datetimes for Rails 3.x and +ActiveModel. + +This is a Rails 4-compatible fork of the +[original validates_timeliness gem][original] by [Adam Meehan][adzap]. + +## Features + +* Adds validation for dates, times and datetimes to ActiveModel +* Handles timezones and type casting of values for you +* Only Rails date/time validation plugin offering complete validation (See + ORM/ODM support) +* Uses extensible date/time parser (Using + [timeliness gem][timeliness]. See Plugin Parser) +* Adds extensions to fix Rails date/time select issues (See Extensions) +* Supports I18n for the error messages +* Supports all the Rubies (that any sane person would be using in production). + +## Installation + + # in Gemfile + gem 'jc-validates_timeliness' + + # Run bundler + $ bundle install + +Then run + + $ rails generate validates_timeliness:install + +This creates configuration initializer and locale files. In the initializer, +there are a number of config options to customize the plugin. + +NOTE: You may wish to enable the plugin parser and the extensions to start. + Please read those sections first. + +## Examples + + validates_datetime :occurred_at + + validates_date :date_of_birth, :before => lambda { 18.years.ago }, + :before_message => "must be at least 18 years old" + + validates_datetime :finish_time, :after => :start_time # Method symbol + + validates_date :booked_at, :on => :create, :on_or_after => :today # See Restriction Shorthand. + + validates_time :booked_at, :between => ['9:00am', '5:00pm'] # On or after 9:00AM and on or before 5:00PM + validates_time :booked_at, :between => '9:00am'..'5:00pm' # The same as previous example + validates_time :booked_at, :between => '9:00am'...'5:00pm' # On or after 9:00AM and strictly before 5:00PM + + validates_time :breakfast_time, :on_or_after => '6:00am', + :on_or_after_message => 'must be after opening time', + :before => :lunchtime, + :before_message => 'must be before lunch time' + +## Usage + +To validate a model with a date, time or datetime attribute you just use the +validation method + + class Person < ActiveRecord::Base + validates_date :date_of_birth, :on_or_before => lambda { Date.current } + # or + validates :date_of_birth, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date} + end + +or even on a specific record, per ActiveModel API. + + @person.validates_date :date_of_birth, :on_or_before => lambda { Date.current } + +The list of validation methods available are as follows: + + validates_date - validate value as date + validates_time - validate value as time only i.e. '12:20pm' + validates_datetime - validate value as a full date and time + validates - use the :timeliness key and set the type in the hash. + +The validation methods take the usual options plus some specific ones to +restrict the valid range of dates or times allowed + +Temporal options (or restrictions): + + :is_at - Attribute must be equal to value to be valid + :before - Attribute must be before this value to be valid + :on_or_before - Attribute must be equal to or before this value to be valid + :after - Attribute must be after this value to be valid + :on_or_after - Attribute must be equal to or after this value to be valid + :between - Attribute must be between the values to be valid. Range or Array of 2 values. + +Regular validation options: + + :allow_nil - Allow a nil value to be valid + :allow_blank - Allows a nil or empty string value to be valid + :if - Execute validation when :if evaluates true + :unless - Execute validation when :unless evaluates false + :on - Specify validation context e.g :save, :create or :update. Default is :save. + +Special options: + + :ignore_usec - Ignores microsecond value on datetime restrictions + :format - Limit validation to a single format for special cases. Requires plugin parser. + +The temporal restrictions can take 4 different value types: + +* Date, Time, or DateTime object value +* Proc or lambda object which may take an optional parameter, being the record + object +* A symbol matching a method name in the model +* String value + +When an attribute value is compared to temporal restrictions, they are +compared as the same type as the validation method type. So using +validates_date means all values are compared as dates. + +## Configuration + +### ORM/ODM Support + +The plugin adds date/time validation to ActiveModel for any ORM/ODM that +supports the ActiveModel validations component. However, there is an issue +with most ORM/ODMs which does not allow 100% date/time validation by default. +Specifically, when you assign an invalid date/time value to an attribute, most +ORM/ODMs will only store a nil value for the attribute. This causes an issue +for date/time validation, since we need to know that a value was assigned but +was invalid. To fix this, we need to cache the original invalid value to know +that the attribute is not just nil. + +Each ORM/ODM requires a specific shim to fix it. The plugin includes a shim +for ActiveRecord and Mongoid. You can activate them like so + + ValidatesTimeliness.setup do |config| + + # Extend ORM/ODMs for full support (:active_record, :mongoid). + config.extend_orms = [ :mongoid ] + + end + +By default the plugin extends ActiveRecord if loaded. If you wish to extend +another ORM then look at the [wiki page][orm-support] for more information. + +It is not required that you use a shim, but you will not catch errors when the +attribute value is invalid and evaluated to nil. + +### Error Messages + +Using the I18n system to define new defaults: + + en: + errors: + messages: + invalid_date: "is not a valid date" + invalid_time: "is not a valid time" + invalid_datetime: "is not a valid datetime" + is_at: "must be at %{restriction}" + before: "must be before %{restriction}" + on_or_before: "must be on or before %{restriction}" + after: "must be after %{restriction}" + on_or_after: "must be on or after %{restriction}" + +The `%{restriction}` signifies where the interpolation value for the +restriction will be inserted. + +You can also use validation options for custom error messages. The following +option keys are available: + + :invalid_date_message + :invalid_time_message + :invalid_datetime_message + :is_at_message + :before_message + :on_or_before_message + :after_message + :on_or_after_message + +Note: There is no :between_message option. The between error message should be +defined using the :on_or_after and :on_or_before (:before in case when +:between argument is a Range with excluded high value, see Examples) messages. + +It is highly recommended you use the I18n system for error messages. + +### Plugin Parser + +The plugin uses the [timeliness gem][timeliness] as a fast, configurable and +extensible date and time parser. You can add or remove valid formats for +dates, times, and datetimes. It is also more strict than the Ruby parser, +which means it won't accept day of the month if it's not a valid number for +the month. + +By default the parser is disabled. To enable it: + + # in the setup block + config.use_plugin_parser = true + +Enabling the parser will mean that strings assigned to attributes validated +with the plugin will be parsed using the gem. See the [wiki][plugin-parser] +for more details about the parser configuration. + + +### Restriction Shorthand + +It is common to restrict an attribute to being on or before the current time +or current day. To specify this you need to use a lambda as an option value +e.g. `lambda { Time.current }. This can be tedious noise amongst your +validations for something so common. To combat this the plugin allows you to +use shorthand symbols for often used relative times or dates. + +Just provide the symbol as the option value like so: + + validates_date :birth_date, :on_or_before => :today + +The :today symbol is evaluated as `lambda { Date.today }`. The :now and :today +symbols are pre-configured. Configure your own like so: + + # in the setup block + config.restriction_shorthand_symbols.update( + :yesterday => lambda { 1.day.ago } + ) + +### Default Timezone + +The plugin needs to know the default timezone you are using when parsing or +type casting values. If you are using ActiveRecord then the default is +automatically set to the same default zone as ActiveRecord. If you are using +another ORM you may need to change this setting. + + # in the setup block + config.default_timezone = :utc + +By default it will be UTC if ActiveRecord is not loaded. + +### Dummy Date For Time Types + +Given that Ruby has no support for a time-only type, all time type columns are +evaluated as a regular Time class objects with a dummy date value set. Rails +defines the dummy date as 2000-01-01. So a time of '12:30' is evaluated as a +Time value of '2000-01-01 12:30'. If you need to customize this for some +reason you can do so as follows + + # in the setup block + config.dummy_date_for_time_type = [2009, 1, 1] + +The value should be an array of 3 values being year, month and day in that +order. + +### Temporal Restriction Errors + +When using the validation temporal restrictions there are times when the +restriction option value itself may be invalid. This will add an error to the +model such as 'Error occurred validating birth_date for :before restriction'. +These can be annoying in development or production as you most likely just +want to skip the option if no valid value was returned. By default these +errors are displayed in Rails test mode. + +To turn them on/off: + + # in the setup block + config.ignore_restriction_errors = true + +## Extensions + +### Strict Parsing for Select Helpers + +When using date/time select helpers, the component values are handled by +ActiveRecord using the Time class to instantiate them into a time value. This +means that some invalid dates, such as 31st June, are shifted forward and +treated as valid. To handle these cases in a strict way, you can enable the +plugin extension to treat them as invalid dates. + +To activate it, uncomment this line in the initializer: + + # in the setup block + config.enable_multiparameter_extension! + +### Display Invalid Values in Select Helpers + +The plugin offers an extension for ActionView to allowing invalid date and +time values to be redisplayed to the user as feedback, instead of a blank +field which happens by default in Rails. Though the date helpers make this a +pretty rare occurrence, given the select dropdowns for each date/time +component, but it may be something of interest. + +To activate it, uncomment this line in the initializer: + + # in the setup block + config.enable_date_time_select_extension! + +## Contributors + +To see the generous people who have contributed code, take a look at the +[contributors list][contributors]. + +## Maintainers + +* [John Carney][jc] + +## License + +Copyright (c) 2008 Adam Meehan, released under the MIT license + +[jc]: http://github.com/johncarney +[adzap]: http://github.com/adzap +[timeliness]: http://github.com/adzap/timeliness +[orm-support]: http://github.com/adzap/validates_timeliness/wiki/ORM-Support +[plugin-parser]: http://github.com/adzap/validates_timeliness/wiki/Plugin-Parser +[original]: http://github.com/adzap/validates_timeliness +[contributors]: http://github.com/johncarney/validates_timeliness/contributors +[gem-badge]: https://badge.fury.io/rb/jc-validates_timeliness.svg +[gem]: http://badge.fury.io/rb/jc-validates_timeliness +[build-badge]: https://travis-ci.org/johncarney/validates_timeliness.svg?branch=master +[build]: https://travis-ci.org/johncarney/validates_timeliness +[coverage-badge]: https://coveralls.io/repos/johncarney/validates_timeliness/badge.png?branch=master +[coverage]: https://coveralls.io/r/johncarney/validates_timeliness?branch=master diff --git a/README.rdoc b/README.rdoc deleted file mode 100644 index fa83d030..00000000 --- a/README.rdoc +++ /dev/null @@ -1,299 +0,0 @@ -= ValidatesTimeliness - -* Source: http://github.com/adzap/validates_timeliness -* Issues: http://github.com/adzap/validates_timeliness/issues - -== Description - -Complete validation of dates, times and datetimes for Rails 3.x and ActiveModel. - -If you a looking for the old version for Rails 2.x go here[http://github.com/adzap/validates_timeliness/tree/v2.3]. - - -== Features - -* Adds validation for dates, times and datetimes to ActiveModel - -* Handles timezones and type casting of values for you - -* Only Rails date/time validation plugin offering complete validation (See ORM/ODM support) - -* Uses extensible date/time parser (Using {timeliness gem}[http://github.com/adzap/timeliness]. See Plugin Parser) - -* Adds extensions to fix Rails date/time select issues (See Extensions) - -* Supports I18n for the error messages - -* Supports all the Rubies (that any sane person would be using in production). - - -== Installation - - # in Gemfile - gem 'validates_timeliness', '~> 3.0' - - # Run bundler - $ bundle install - -Then run - - $ rails generate validates_timeliness:install - -This creates configuration initializer and locale files. In the initializer, there are a number of config -options to customize the plugin. - -NOTE: You may wish to enable the plugin parser and the extensions to start. Please read those sections first. - - -== Examples - - validates_datetime :occurred_at - - validates_date :date_of_birth, :before => lambda { 18.years.ago }, - :before_message => "must be at least 18 years old" - - validates_datetime :finish_time, :after => :start_time # Method symbol - - validates_date :booked_at, :on => :create, :on_or_after => :today # See Restriction Shorthand. - - validates_time :booked_at, :between => ['9:00am', '5:00pm'] # On or after 9:00AM and on or before 5:00PM - validates_time :booked_at, :between => '9:00am'..'5:00pm' # The same as previous example - validates_time :booked_at, :between => '9:00am'...'5:00pm' # On or after 9:00AM and strictly before 5:00PM - - validates_time :breakfast_time, :on_or_after => '6:00am', - :on_or_after_message => 'must be after opening time', - :before => :lunchtime, - :before_message => 'must be before lunch time' - - -== Usage - -To validate a model with a date, time or datetime attribute you just use the -validation method - - class Person < ActiveRecord::Base - validates_date :date_of_birth, :on_or_before => lambda { Date.current } - # or - validates :date_of_birth, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date} - end - -or even on a specific record, per ActiveModel API. - - @person.validates_date :date_of_birth, :on_or_before => lambda { Date.current } - - -The list of validation methods available are as follows: - validates_date - validate value as date - validates_time - validate value as time only i.e. '12:20pm' - validates_datetime - validate value as a full date and time - validates - use the :timeliness key and set the type in the hash. - -The validation methods take the usual options plus some specific ones to restrict -the valid range of dates or times allowed - -Temporal options (or restrictions): - :is_at - Attribute must be equal to value to be valid - :before - Attribute must be before this value to be valid - :on_or_before - Attribute must be equal to or before this value to be valid - :after - Attribute must be after this value to be valid - :on_or_after - Attribute must be equal to or after this value to be valid - :between - Attribute must be between the values to be valid. Range or Array of 2 values. - -Regular validation options: - :allow_nil - Allow a nil value to be valid - :allow_blank - Allows a nil or empty string value to be valid - :if - Execute validation when :if evaluates true - :unless - Execute validation when :unless evaluates false - :on - Specify validation context e.g :save, :create or :update. Default is :save. - -Special options: - :ignore_usec - Ignores microsecond value on datetime restrictions - :format - Limit validation to a single format for special cases. Requires plugin parser. - -The temporal restrictions can take 4 different value types: - -* Date, Time, or DateTime object value -* Proc or lambda object which may take an optional parameter, being the record object -* A symbol matching a method name in the model -* String value - -When an attribute value is compared to temporal restrictions, they are compared as -the same type as the validation method type. So using validates_date means all -values are compared as dates. - - -== Configuration - -=== ORM/ODM Support - -The plugin adds date/time validation to ActiveModel for any ORM/ODM that supports the ActiveModel validations component. -However, there is an issue with most ORM/ODMs which does not allow 100% date/time validation by default. Specifically, when you -assign an invalid date/time value to an attribute, most ORM/ODMs will only store a nil value for the attribute. This causes an -issue for date/time validation, since we need to know that a value was assigned but was invalid. To fix this, we need to cache -the original invalid value to know that the attribute is not just nil. - -Each ORM/ODM requires a specific shim to fix it. The plugin includes a shim for ActiveRecord and Mongoid. You can activate them -like so - - ValidatesTimeliness.setup do |config| - - # Extend ORM/ODMs for full support (:active_record, :mongoid). - config.extend_orms = [ :mongoid ] - - end - -By default the plugin extends ActiveRecord if loaded. If you wish to extend another ORM then look at the {wiki page}[http://github.com/adzap/validates_timeliness/wiki/ORM-Support] for more information. - -It is not required that you use a shim, but you will not catch errors when the attribute value is invalid and evaluated to nil. - - -=== Error Messages - -Using the I18n system to define new defaults: - - en: - errors: - messages: - invalid_date: "is not a valid date" - invalid_time: "is not a valid time" - invalid_datetime: "is not a valid datetime" - is_at: "must be at %{restriction}" - before: "must be before %{restriction}" - on_or_before: "must be on or before %{restriction}" - after: "must be after %{restriction}" - on_or_after: "must be on or after %{restriction}" - -The %{restriction} signifies where the interpolation value for the restriction will be inserted. - -You can also use validation options for custom error messages. The following option keys are available: - - :invalid_date_message - :invalid_time_message - :invalid_datetime_message - :is_at_message - :before_message - :on_or_before_message - :after_message - :on_or_after_message - -Note: There is no :between_message option. The between error message should be defined using the :on_or_after and :on_or_before -(:before in case when :between argument is a Range with excluded high value, see Examples) messages. - -It is highly recommended you use the I18n system for error messages. - - -=== Plugin Parser - -The plugin uses the {timeliness gem}[http://github.com/adzap/timeliness] as a fast, configurable and extensible date and time parser. -You can add or remove valid formats for dates, times, and datetimes. It is also more strict than the -Ruby parser, which means it won't accept day of the month if it's not a valid number for the month. - -By default the parser is disabled. To enable it: - - # in the setup block - config.use_plugin_parser = true - -Enabling the parser will mean that strings assigned to attributes validated with the plugin will be parsed -using the gem. See the wiki[http://github.com/adzap/validates_timeliness/wiki/Plugin-Parser] for more details about the parser configuration. - - -=== Restriction Shorthand - -It is common to restrict an attribute to being on or before the current time or current day. -To specify this you need to use a lambda as an option value e.g. lambda { Time.current }. -This can be tedious noise amongst your validations for something so common. To combat this the -plugin allows you to use shorthand symbols for often used relative times or dates. - -Just provide the symbol as the option value like so: - - validates_date :birth_date, :on_or_before => :today - -The :today symbol is evaluated as lambda { Date.today }. The :now and :today -symbols are pre-configured. Configure your own like so: - - # in the setup block - config.restriction_shorthand_symbols.update( - :yesterday => lambda { 1.day.ago } - ) - - -=== Default Timezone - -The plugin needs to know the default timezone you are using when parsing or type casting values. If you are using -ActiveRecord then the default is automatically set to the same default zone as ActiveRecord. If you are using -another ORM you may need to change this setting. - - # in the setup block - config.default_timezone = :utc - -By default it will be UTC if ActiveRecord is not loaded. - - -=== Dummy Date For Time Types - -Given that Ruby has no support for a time-only type, all time type columns are evaluated -as a regular Time class objects with a dummy date value set. Rails defines the dummy date as -2000-01-01. So a time of '12:30' is evaluated as a Time value of '2000-01-01 12:30'. If you -need to customize this for some reason you can do so as follows - - # in the setup block - config.dummy_date_for_time_type = [2009, 1, 1] - -The value should be an array of 3 values being year, month and day in that order. - - -=== Temporal Restriction Errors - -When using the validation temporal restrictions there are times when the restriction -option value itself may be invalid. This will add an error to the model such as -'Error occurred validating birth_date for :before restriction'. These can be annoying -in development or production as you most likely just want to skip the option if no -valid value was returned. By default these errors are displayed in Rails test mode. - -To turn them on/off: - - # in the setup block - config.ignore_restriction_errors = true - - -== Extensions - -=== Strict Parsing for Select Helpers - -When using date/time select helpers, the component values are handled by ActiveRecord using -the Time class to instantiate them into a time value. This means that some invalid dates, -such as 31st June, are shifted forward and treated as valid. To handle these cases in a strict -way, you can enable the plugin extension to treat them as invalid dates. - -To activate it, uncomment this line in the initializer: - - # in the setup block - config.enable_multiparameter_extension! - - -=== Display Invalid Values in Select Helpers - -The plugin offers an extension for ActionView to allowing invalid date and time values to be -redisplayed to the user as feedback, instead of a blank field which happens by default in -Rails. Though the date helpers make this a pretty rare occurrence, given the select dropdowns -for each date/time component, but it may be something of interest. - -To activate it, uncomment this line in the initializer: - - # in the setup block - config.enable_date_time_select_extension! - - -== Contributors - -To see the generous people who have contributed code, take a look at the {contributors list}[http://github.com/adzap/validates_timeliness/contributors]. - - -== Maintainers - -* {Adam Meehan}[http://github.com/adzap] - - -== License - -Copyright (c) 2008 Adam Meehan, released under the MIT license diff --git a/lib/jc-validates_timeliness.rb b/lib/jc-validates_timeliness.rb new file mode 100644 index 00000000..12b82d4c --- /dev/null +++ b/lib/jc-validates_timeliness.rb @@ -0,0 +1 @@ +require "validates_timeliness" diff --git a/lib/validates_timeliness/attribute_methods.rb b/lib/validates_timeliness/attribute_methods.rb index 2b4993d5..e8e5936b 100644 --- a/lib/validates_timeliness/attribute_methods.rb +++ b/lib/validates_timeliness/attribute_methods.rb @@ -46,7 +46,7 @@ def #{attr_name}=(value) @timeliness_cache ||= {} @timeliness_cache["#{attr_name}"] = original_value #{ "if value.is_a?(String)\n#{timeliness_type_cast_code(attr_name, 'value')}\nend" if ValidatesTimeliness.use_plugin_parser } - + super(value) end EOV @@ -56,7 +56,10 @@ def #{attr_name}=(value) def define_timeliness_before_type_cast_method(attr_name) method_body, line = <<-EOV, __LINE__ + 1 def #{attr_name}_before_type_cast - _timeliness_raw_value_for('#{attr_name}') || @attributes['#{attr_name}'] + _timeliness_raw_value_for('#{attr_name}') || begin + a = @attributes['#{attr_name}'] + a.respond_to?(:value_before_type_cast) ? a.value_before_type_cast : a + end end EOV generated_timeliness_methods.module_eval(method_body, __FILE__, line) diff --git a/lib/validates_timeliness/conversion.rb b/lib/validates_timeliness/conversion.rb index 7bd26d04..93e498ad 100644 --- a/lib/validates_timeliness/conversion.rb +++ b/lib/validates_timeliness/conversion.rb @@ -60,7 +60,7 @@ def parse(value) if ValidatesTimeliness.use_plugin_parser Timeliness::Parser.parse(value, @type, :zone => (:current if @timezone_aware), :format => options[:format], :strict => false) else - @timezone_aware ? Time.zone.parse(value) : value.to_time(ValidatesTimeliness.default_timezone) + @timezone_aware ? Time.zone.parse(value, Time.zone.now) : value.to_time(ValidatesTimeliness.default_timezone) end rescue ArgumentError, TypeError nil diff --git a/lib/validates_timeliness/validator.rb b/lib/validates_timeliness/validator.rb index 806dbe2b..5610b1d1 100644 --- a/lib/validates_timeliness/validator.rb +++ b/lib/validates_timeliness/validator.rb @@ -23,6 +23,10 @@ class Validator < ActiveModel::EachValidator RESTRICTION_ERROR_MESSAGE = "Error occurred validating %s for %s restriction:\n%s" + # Prior to version 4.1, Rails will call `#setup`, if defined. This method is deprecated in Rails 4.1 and removed + # altogether in 4.2. + SETUP_DEPRECATED = ActiveModel.respond_to?(:version) && ActiveModel.version >= Gem::Version.new('4.1') + def self.kind :timeliness end @@ -43,15 +47,19 @@ def initialize(options) @restrictions_to_check = RESTRICTIONS.keys & options.keys super + setup_timeliness_validated_attributes(options[:class]) if options[:class] end - def setup(model) + def setup_timeliness_validated_attributes(model) if model.respond_to?(:timeliness_validated_attributes) model.timeliness_validated_attributes ||= [] model.timeliness_validated_attributes |= @attributes end end + # Provide backwards compatibility for Rails < 4.1, which expects `#setup` to be defined. + alias_method :setup, :setup_timeliness_validated_attributes unless SETUP_DEPRECATED + def validate_each(record, attr_name, value) raw_value = attribute_raw_value(record, attr_name) || value return if (@allow_nil && raw_value.nil?) || (@allow_blank && raw_value.blank?) diff --git a/lib/validates_timeliness/version.rb b/lib/validates_timeliness/version.rb index 9865e5d4..f565fb2d 100644 --- a/lib/validates_timeliness/version.rb +++ b/lib/validates_timeliness/version.rb @@ -1,3 +1,3 @@ module ValidatesTimeliness - VERSION = '3.0.14' + VERSION = '3.1.1' end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 4afcd565..f110301a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,17 +1,25 @@ require 'rspec' +require 'rspec/collection_matchers' + +# Coveralls +require "coveralls" + +Coveralls.wear! do + add_filter 'spec' +end require 'active_model' require 'active_model/validations' require 'active_record' require 'action_view' require 'timecop' -require 'rspec_tag_matchers' require 'validates_timeliness' require 'support/test_model' require 'support/model_helpers' require 'support/config_helper' +require 'support/tag_matcher' ValidatesTimeliness.setup do |c| c.extend_orms = [ :active_record ] @@ -57,6 +65,8 @@ class PersonWithShim < Person include TestModelShim end +I18n.enforce_available_locales = false + ActiveRecord::Base.default_timezone = :utc ActiveRecord::Base.time_zone_aware_attributes = true ActiveRecord::Base.establish_connection({:adapter => 'sqlite3', :database => ':memory:'}) @@ -85,9 +95,9 @@ def birth_date=(value) RSpec.configure do |c| c.mock_with :rspec - c.include(RspecTagMatchers) c.include(ModelHelpers) c.include(ConfigHelper) + c.include(TagMatcher) c.before do reset_validation_setup_for(Person) reset_validation_setup_for(PersonWithShim) diff --git a/spec/support/model_helpers.rb b/spec/support/model_helpers.rb index caaac30b..b9a940b1 100644 --- a/spec/support/model_helpers.rb +++ b/spec/support/model_helpers.rb @@ -3,15 +3,15 @@ module ModelHelpers # Some test helpers from Rails source def invalid!(attr_name, values, error = nil) with_each_person_value(attr_name, values) do |record, value| - record.should be_invalid - record.errors[attr_name].size.should >= 1 - record.errors[attr_name].first.should == error if error + expect(record).to be_invalid + expect(record.errors[attr_name].size).to be >= 1 + expect(record.errors[attr_name].first).to eq(error) if error end end def valid!(attr_name, values) with_each_person_value(attr_name, values) do |record, value| - record.should be_valid + expect(record).to be_valid end end diff --git a/spec/support/tag_matcher.rb b/spec/support/tag_matcher.rb new file mode 100644 index 00000000..2fe98707 --- /dev/null +++ b/spec/support/tag_matcher.rb @@ -0,0 +1,35 @@ +require 'nokogiri' + +module TagMatcher + extend RSpec::Matchers::DSL + + matcher :have_tag do |selector| + match do |subject| + matches = doc(subject).search(selector) + + if @inner_text + matches = matches.select { |element| element.inner_text == @inner_text } + end + + matches.any? + end + + chain :with_inner_text do |inner_text| + @inner_text = inner_text + end + + private + + def body(subject) + if subject.respond_to?(:body) + subject.body + else + subject.to_s + end + end + + def doc(subject) + @doc ||= Nokogiri::HTML(body(subject)) + end + end +end diff --git a/spec/support/test_model.rb b/spec/support/test_model.rb index 813802fe..e594b3ce 100644 --- a/spec/support/test_model.rb +++ b/spec/support/test_model.rb @@ -5,7 +5,6 @@ module TestModel include ActiveModel::AttributeMethods included do - attribute_method_suffix "" attribute_method_suffix "=" cattr_accessor :model_attributes end diff --git a/spec/validates_timeliness/attribute_methods_spec.rb b/spec/validates_timeliness/attribute_methods_spec.rb index 7d4576ce..aa3f7ce3 100644 --- a/spec/validates_timeliness/attribute_methods_spec.rb +++ b/spec/validates_timeliness/attribute_methods_spec.rb @@ -2,7 +2,7 @@ describe ValidatesTimeliness::AttributeMethods do it 'should define _timeliness_raw_value_for instance method' do - PersonWithShim.new.should respond_to(:_timeliness_raw_value_for) + expect(PersonWithShim.new).to respond_to(:_timeliness_raw_value_for) end describe ".timeliness_validated_attributes" do @@ -12,10 +12,10 @@ PersonWithShim.validates_time :birth_time PersonWithShim.validates_datetime :birth_datetime - PersonWithShim.timeliness_validated_attributes.should == [ :birth_date, :birth_time, :birth_datetime ] + expect(PersonWithShim.timeliness_validated_attributes).to eq([ :birth_date, :birth_time, :birth_datetime ]) end end - + context "attribute write method" do class PersonWithCache include TestModel @@ -31,13 +31,13 @@ class PersonWithCache it 'should cache attribute raw value' do r = PersonWithCache.new r.birth_datetime = date_string = '2010-01-01' - r._timeliness_raw_value_for('birth_datetime').should == date_string + expect(r._timeliness_raw_value_for('birth_datetime')).to eq(date_string) end it 'should not overwrite user defined methods' do e = Employee.new e.birth_date = '2010-01-01' - e.redefined_birth_date_called.should be_true + expect(e.redefined_birth_date_called).to be_truthy end it 'should be undefined if model class has dynamic attribute methods reset' do @@ -48,11 +48,11 @@ class PersonWithCache write_method = RUBY_VERSION < '1.9' ? 'birth_date=' : :birth_date= - PersonWithShim.send(:generated_timeliness_methods).instance_methods.should include(write_method) + expect(PersonWithShim.send(:generated_timeliness_methods).instance_methods).to include(write_method) - PersonWithShim.undefine_attribute_methods + PersonWithShim.undefine_attribute_methods - PersonWithShim.send(:generated_timeliness_methods).instance_methods.should_not include(write_method) + expect(PersonWithShim.send(:generated_timeliness_methods).instance_methods).not_to include(write_method) end context "with plugin parser" do @@ -70,7 +70,7 @@ class PersonWithParser end it 'should parse a string value' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) r = PersonWithParser.new r.birth_date = '2010-01-01' end @@ -80,7 +80,7 @@ class PersonWithParser context "before_type_cast method" do it 'should not be defined if ORM does not support it' do - PersonWithShim.new.should_not respond_to(:birth_datetime_before_type_cast) + expect(PersonWithShim.new).not_to respond_to(:birth_datetime_before_type_cast) end end end diff --git a/spec/validates_timeliness/conversion_spec.rb b/spec/validates_timeliness/conversion_spec.rb index 88eb693e..2fc626e1 100644 --- a/spec/validates_timeliness/conversion_spec.rb +++ b/spec/validates_timeliness/conversion_spec.rb @@ -12,68 +12,68 @@ describe "#type_cast_value" do describe "for date type" do it "should return same value for date value" do - type_cast_value(Date.new(2010, 1, 1), :date).should == Date.new(2010, 1, 1) + expect(type_cast_value(Date.new(2010, 1, 1), :date)).to eq(Date.new(2010, 1, 1)) end it "should return date part of time value" do - type_cast_value(Time.mktime(2010, 1, 1, 0, 0, 0), :date).should == Date.new(2010, 1, 1) + expect(type_cast_value(Time.mktime(2010, 1, 1, 0, 0, 0), :date)).to eq(Date.new(2010, 1, 1)) end it "should return date part of datetime value" do - type_cast_value(DateTime.new(2010, 1, 1, 0, 0, 0), :date).should == Date.new(2010, 1, 1) + expect(type_cast_value(DateTime.new(2010, 1, 1, 0, 0, 0), :date)).to eq(Date.new(2010, 1, 1)) end it 'should return nil for invalid value types' do - type_cast_value(12, :date).should == nil + expect(type_cast_value(12, :date)).to eq(nil) end end describe "for time type" do it "should return same value for time value matching dummy date part" do - type_cast_value(Time.utc(2000, 1, 1, 0, 0, 0), :time).should == Time.utc(2000, 1, 1, 0, 0, 0) + expect(type_cast_value(Time.utc(2000, 1, 1, 0, 0, 0), :time)).to eq(Time.utc(2000, 1, 1, 0, 0, 0)) end it "should return dummy time value with same time part for time value with different date" do - type_cast_value(Time.utc(2010, 1, 1, 0, 0, 0), :time).should == Time.utc(2000, 1, 1, 0, 0, 0) + expect(type_cast_value(Time.utc(2010, 1, 1, 0, 0, 0), :time)).to eq(Time.utc(2000, 1, 1, 0, 0, 0)) end it "should return dummy time only for date value" do - type_cast_value(Date.new(2010, 1, 1), :time).should == Time.utc(2000, 1, 1, 0, 0, 0) + expect(type_cast_value(Date.new(2010, 1, 1), :time)).to eq(Time.utc(2000, 1, 1, 0, 0, 0)) end it "should return dummy date with time part for datetime value" do - type_cast_value(DateTime.civil_from_format(:utc, 2010, 1, 1, 12, 34, 56), :time).should == Time.utc(2000, 1, 1, 12, 34, 56) + expect(type_cast_value(DateTime.civil_from_format(:utc, 2010, 1, 1, 12, 34, 56), :time)).to eq(Time.utc(2000, 1, 1, 12, 34, 56)) end it 'should return nil for invalid value types' do - type_cast_value(12, :time).should == nil + expect(type_cast_value(12, :time)).to eq(nil) end end describe "for datetime type" do it "should return Date as Time value" do - type_cast_value(Date.new(2010, 1, 1), :datetime).should == Time.local_time(2010, 1, 1, 0, 0, 0) + expect(type_cast_value(Date.new(2010, 1, 1), :datetime)).to eq(Time.local_time(2010, 1, 1, 0, 0, 0)) end it "should return same Time value" do value = Time.utc(2010, 1, 1, 12, 34, 56) - type_cast_value(Time.utc(2010, 1, 1, 12, 34, 56), :datetime).should == value + expect(type_cast_value(Time.utc(2010, 1, 1, 12, 34, 56), :datetime)).to eq(value) end it "should return as Time with same component values" do - type_cast_value(DateTime.civil_from_format(:utc, 2010, 1, 1, 12, 34, 56), :datetime).should == Time.utc(2010, 1, 1, 12, 34, 56) + expect(type_cast_value(DateTime.civil_from_format(:utc, 2010, 1, 1, 12, 34, 56), :datetime)).to eq(Time.utc(2010, 1, 1, 12, 34, 56)) end it "should return same Time in correct zone if timezone aware" do @timezone_aware = true value = Time.utc(2010, 1, 1, 12, 34, 56) result = type_cast_value(value, :datetime) - result.should == Time.zone.local(2010, 1, 1, 23, 34, 56) - result.zone.should == 'EST' + expect(result).to eq(Time.zone.local(2010, 1, 1, 23, 34, 56)) + expect(result.zone).to eq('AEDT') # 'Australia/Melbourne' end it 'should return nil for invalid value types' do - type_cast_value(12, :datetime).should == nil + expect(type_cast_value(12, :datetime)).to eq(nil) end end @@ -82,41 +82,41 @@ it "should ignore usec on time values when evaluated" do value = Time.utc(2010, 1, 1, 12, 34, 56, 10000) - type_cast_value(value, :datetime).should == Time.utc(2010, 1, 1, 12, 34, 56) + expect(type_cast_value(value, :datetime)).to eq(Time.utc(2010, 1, 1, 12, 34, 56)) end it "should ignore usec and return time in correct zone if timezone aware" do @timezone_aware = true value = Time.utc(2010, 1, 1, 12, 34, 56, 10000) result = type_cast_value(value, :datetime) - result.should == Time.zone.local(2010, 1, 1, 23, 34, 56) - result.zone.should == 'EST' + expect(result).to eq(Time.zone.local(2010, 1, 1, 23, 34, 56)) + expect(result.zone).to eq('AEDT') # 'Australia/Melbourne' end end end describe "#dummy_time" do it 'should return Time with dummy date values but same time components' do - dummy_time(Time.utc(2010, 11, 22, 12, 34, 56)).should == Time.utc(2000, 1, 1, 12, 34, 56) + expect(dummy_time(Time.utc(2010, 11, 22, 12, 34, 56))).to eq(Time.utc(2000, 1, 1, 12, 34, 56)) end it 'should return same value for Time which already has dummy date values' do - dummy_time(Time.utc(2000, 1, 1, 12, 34, 56)).should == Time.utc(2000, 1, 1, 12, 34, 56) + expect(dummy_time(Time.utc(2000, 1, 1, 12, 34, 56))).to eq(Time.utc(2000, 1, 1, 12, 34, 56)) end it 'should return time component values shifted to current zone if timezone aware' do @timezone_aware = true - dummy_time(Time.utc(2000, 1, 1, 12, 34, 56)).should == Time.zone.local(2000, 1, 1, 23, 34, 56) + expect(dummy_time(Time.utc(2000, 1, 1, 12, 34, 56))).to eq(Time.zone.local(2000, 1, 1, 23, 34, 56)) end it 'should return base dummy time value for Date value' do - dummy_time(Date.new(2010, 11, 22)).should == Time.utc(2000, 1, 1, 0, 0, 0) + expect(dummy_time(Date.new(2010, 11, 22))).to eq(Time.utc(2000, 1, 1, 0, 0, 0)) end describe "with custom dummy date" do it 'should return dummy time with custom dummy date' do with_config(:dummy_date_for_time_type, [2010, 1, 1] ) do - dummy_time(Time.utc(1999, 11, 22, 12, 34, 56)).should == Time.utc(2010, 1, 1, 12, 34, 56) + expect(dummy_time(Time.utc(1999, 11, 22, 12, 34, 56))).to eq(Time.utc(2010, 1, 1, 12, 34, 56)) end end end @@ -127,56 +127,56 @@ it 'should return Date object as is' do value = Date.new(2010,1,1) - evaluate_option_value(value, person).should == value + expect(evaluate_option_value(value, person)).to eq(value) end it 'should return Time object as is' do value = Time.mktime(2010,1,1) - evaluate_option_value(value, person).should == value + expect(evaluate_option_value(value, person)).to eq(value) end it 'should return DateTime object as is' do value = DateTime.new(2010,1,1,0,0,0) - evaluate_option_value(value, person).should == value + expect(evaluate_option_value(value, person)).to eq(value) end it 'should return Time value returned from proc with 0 arity' do value = Time.mktime(2010,1,1) - evaluate_option_value(lambda { value }, person).should == value + expect(evaluate_option_value(lambda { value }, person)).to eq(value) end it 'should return Time value returned by record attribute call in proc arity of 1' do value = Time.mktime(2010,1,1) person.birth_time = value - evaluate_option_value(lambda {|r| r.birth_time }, person).should == value + expect(evaluate_option_value(lambda {|r| r.birth_time }, person)).to eq(value) end it 'should return Time value for attribute method symbol which returns Time' do value = Time.mktime(2010,1,1) person.birth_time = value - evaluate_option_value(:birth_time, person).should == value + expect(evaluate_option_value(:birth_time, person)).to eq(value) end it 'should return Time value is default zone from string time value' do value = '2010-01-01 12:00:00' - evaluate_option_value(value, person).should == Time.utc(2010,1,1,12,0,0) + expect(evaluate_option_value(value, person)).to eq(Time.utc(2010,1,1,12,0,0)) end it 'should return Time value is current zone from string time value if timezone aware' do @timezone_aware = true value = '2010-01-01 12:00:00' - evaluate_option_value(value, person).should == Time.zone.local(2010,1,1,12,0,0) + expect(evaluate_option_value(value, person)).to eq(Time.zone.local(2010,1,1,12,0,0)) end it 'should return Time value in default zone from proc which returns string time' do value = '2010-01-01 12:00:00' - evaluate_option_value(lambda { value }, person).should == Time.utc(2010,1,1,12,0,0) + expect(evaluate_option_value(lambda { value }, person)).to eq(Time.utc(2010,1,1,12,0,0)) end it 'should return Time value for attribute method symbol which returns string time value' do value = '2010-01-01 12:00:00' person.birth_time = value - evaluate_option_value(:birth_time, person).should == Time.utc(2010,1,1,12,0,0) + expect(evaluate_option_value(:birth_time, person)).to eq(Time.utc(2010,1,1,12,0,0)) end context "restriction shorthand" do @@ -185,17 +185,17 @@ end it 'should evaluate :now as current time' do - evaluate_option_value(:now, person).should == Time.now + expect(evaluate_option_value(:now, person)).to eq(Time.now) end it 'should evaluate :today as current time' do - evaluate_option_value(:today, person).should == Date.today + expect(evaluate_option_value(:today, person)).to eq(Date.today) end it 'should not use shorthand if symbol if is record method' do time = 1.day.from_now - person.stub!(:now).and_return(time) - evaluate_option_value(:now, person).should == time + allow(person).to receive(:now).and_return(time) + expect(evaluate_option_value(:now, person)).to eq(time) end end end @@ -205,7 +205,7 @@ with_config(:use_plugin_parser, true) it 'should use timeliness' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) parse('2000-01-01') end end @@ -215,20 +215,20 @@ it 'should use Time.zone.parse attribute is timezone aware' do @timezone_aware = true - Time.zone.should_receive(:parse) + expect(Time.zone).to receive(:parse) parse('2000-01-01') end it 'should use value#to_time if use_plugin_parser setting is false and attribute is not timezone aware' do @timezone_aware = false value = '2000-01-01' - value.should_receive(:to_time) + expect(value).to receive(:to_time) parse(value) end end it 'should return nil if value is nil' do - parse(nil).should be_nil + expect(parse(nil)).to be_nil end end end diff --git a/spec/validates_timeliness/extensions/date_time_select_spec.rb b/spec/validates_timeliness/extensions/date_time_select_spec.rb index dcfe15f5..5e92c5cd 100644 --- a/spec/validates_timeliness/extensions/date_time_select_spec.rb +++ b/spec/validates_timeliness/extensions/date_time_select_spec.rb @@ -111,7 +111,7 @@ @output = date_select(:person, :birth_date, :include_blank => true, :discard_day => true) should_have_datetime_selected(:birth_date, :year => 2009, :month => 'February') should_not_have_datetime_selected(:birth_time, :day) - @output.should have_tag("input[id=person_birth_date_3i][type=hidden][value='1']") + expect(@output).to have_tag("input[id=person_birth_date_3i][type=hidden][value='1']") end end @@ -150,14 +150,14 @@ def should_have_datetime_selected(field, datetime_hash) datetime_hash.each do |key, value| index = {:year => 1, :month => 2, :day => 3, :hour => 4, :min => 5, :sec => 6}[key] - @output.should have_tag("select[id=person_#{field}_#{index}i] option[selected=selected]", value.to_s) + expect(@output).to have_tag("select[id=person_#{field}_#{index}i] option[selected=selected]").with_inner_text(value.to_s) end end def should_not_have_datetime_selected(field, *attributes) attributes.each do |attribute| index = {:year => 1, :month => 2, :day => 3, :hour => 4, :min => 5, :sec => 6}[attribute] - @output.should_not have_tag("select[id=person_#{attribute}_#{index}i] option[selected=selected]") + expect(@output).not_to have_tag("select[id=person_#{attribute}_#{index}i] option[selected=selected]") end end end diff --git a/spec/validates_timeliness/extensions/multiparameter_handler_spec.rb b/spec/validates_timeliness/extensions/multiparameter_handler_spec.rb index 3a578c08..66c2682f 100644 --- a/spec/validates_timeliness/extensions/multiparameter_handler_spec.rb +++ b/spec/validates_timeliness/extensions/multiparameter_handler_spec.rb @@ -5,34 +5,34 @@ context "time column" do it 'should assign a string value for invalid date portion' do employee = record_with_multiparameter_attribute(:birth_datetime, [2000, 2, 31, 12, 0, 0]) - employee.birth_datetime_before_type_cast.should eq '2000-02-31 12:00:00' + expect(employee.birth_datetime_before_type_cast).to eq '2000-02-31 12:00:00' end it 'should assign a Time value for valid datetimes' do employee = record_with_multiparameter_attribute(:birth_datetime, [2000, 2, 28, 12, 0, 0]) - employee.birth_datetime_before_type_cast.should eq Time.zone.local(2000, 2, 28, 12, 0, 0) + expect(employee.birth_datetime_before_type_cast).to eq Time.zone.local(2000, 2, 28, 12, 0, 0) end it 'should assign a string value for incomplete time' do employee = record_with_multiparameter_attribute(:birth_datetime, [2000, nil, nil]) - employee.birth_datetime_before_type_cast.should eq '2000-00-00' + expect(employee.birth_datetime_before_type_cast).to eq '2000-00-00' end end context "date column" do it 'should assign a string value for invalid date' do employee = record_with_multiparameter_attribute(:birth_date, [2000, 2, 31]) - employee.birth_date_before_type_cast.should eq '2000-02-31' + expect(employee.birth_date_before_type_cast).to eq '2000-02-31' end it 'should assign a Date value for valid date' do employee = record_with_multiparameter_attribute(:birth_date, [2000, 2, 28]) - employee.birth_date_before_type_cast.should eq Date.new(2000, 2, 28) + expect(employee.birth_date_before_type_cast).to eq Date.new(2000, 2, 28) end it 'should assign a string value for incomplete date' do employee = record_with_multiparameter_attribute(:birth_date, [2000, nil, nil]) - employee.birth_date_before_type_cast.should eq '2000-00-00' + expect(employee.birth_date_before_type_cast).to eq '2000-00-00' end end diff --git a/spec/validates_timeliness/helper_methods_spec.rb b/spec/validates_timeliness/helper_methods_spec.rb index f2fb8105..dbc19beb 100644 --- a/spec/validates_timeliness/helper_methods_spec.rb +++ b/spec/validates_timeliness/helper_methods_spec.rb @@ -4,27 +4,27 @@ let(:record) { Person.new } it 'should define class validation methods' do - Person.should respond_to(:validates_date) - Person.should respond_to(:validates_time) - Person.should respond_to(:validates_datetime) + expect(Person).to respond_to(:validates_date) + expect(Person).to respond_to(:validates_time) + expect(Person).to respond_to(:validates_datetime) end it 'should define instance validation methods' do - record.should respond_to(:validates_date) - record.should respond_to(:validates_time) - record.should respond_to(:validates_datetime) + expect(record).to respond_to(:validates_date) + expect(record).to respond_to(:validates_time) + expect(record).to respond_to(:validates_datetime) end it 'should validate instance using class validation defined' do Person.validates_date :birth_date record.valid? - record.errors[:birth_date].should_not be_empty + expect(record.errors[:birth_date]).not_to be_empty end it 'should validate instance using instance valiation method' do record.validates_date :birth_date - record.errors[:birth_date].should_not be_empty + expect(record.errors[:birth_date]).not_to be_empty end end diff --git a/spec/validates_timeliness/orm/active_record_spec.rb b/spec/validates_timeliness/orm/active_record_spec.rb index 531348de..a163d38e 100644 --- a/spec/validates_timeliness/orm/active_record_spec.rb +++ b/spec/validates_timeliness/orm/active_record_spec.rb @@ -6,41 +6,41 @@ let(:record) { Employee.new } it 'should be defined for the class' do - ActiveRecord::Base.should respond_to(:validates_date) - ActiveRecord::Base.should respond_to(:validates_time) - ActiveRecord::Base.should respond_to(:validates_datetime) + expect(ActiveRecord::Base).to respond_to(:validates_date) + expect(ActiveRecord::Base).to respond_to(:validates_time) + expect(ActiveRecord::Base).to respond_to(:validates_datetime) end it 'should defines for the instance' do - record.should respond_to(:validates_date) - record.should respond_to(:validates_time) - record.should respond_to(:validates_datetime) + expect(record).to respond_to(:validates_date) + expect(record).to respond_to(:validates_time) + expect(record).to respond_to(:validates_datetime) end it "should validate a valid value string" do record.birth_date = '2012-01-01' record.valid? - record.errors[:birth_date].should be_empty + expect(record.errors[:birth_date]).to be_empty end it "should validate a invalid value string" do record.birth_date = 'not a date' record.valid? - record.errors[:birth_date].should_not be_empty + expect(record.errors[:birth_date]).not_to be_empty end it "should validate a nil value" do record.birth_date = nil record.valid? - record.errors[:birth_date].should be_empty + expect(record.errors[:birth_date]).to be_empty end end it 'should determine type for attribute' do - Employee.timeliness_attribute_type(:birth_date).should eq :date + expect(Employee.timeliness_attribute_type(:birth_date)).to eq :date end context 'attribute timezone awareness' do @@ -58,21 +58,21 @@ context 'for column attribute' do it 'should be detected from column type' do - klass.timeliness_attribute_timezone_aware?(:birth_date).should be_false - klass.timeliness_attribute_timezone_aware?(:birth_time).should be_false - klass.timeliness_attribute_timezone_aware?(:birth_datetime).should be_true + expect(klass.timeliness_attribute_timezone_aware?(:birth_date)).to be_falsey + expect(klass.timeliness_attribute_timezone_aware?(:birth_time)).to be_falsey + expect(klass.timeliness_attribute_timezone_aware?(:birth_datetime)).to be_truthy end end context 'for non-column attribute' do it 'should be detected from the validation type' do - klass.timeliness_attribute_timezone_aware?(:some_date).should be_false - klass.timeliness_attribute_timezone_aware?(:some_time).should be_false - klass.timeliness_attribute_timezone_aware?(:some_datetime).should be_true + expect(klass.timeliness_attribute_timezone_aware?(:some_date)).to be_falsey + expect(klass.timeliness_attribute_timezone_aware?(:some_time)).to be_falsey + expect(klass.timeliness_attribute_timezone_aware?(:some_datetime)).to be_truthy end end end - + context "attribute write method" do class EmployeeWithCache < ActiveRecord::Base self.table_name = 'employees' @@ -88,7 +88,7 @@ class EmployeeWithCache < ActiveRecord::Base it 'should store raw value' do record.birth_datetime = datetime_string = '2010-01-01 12:30' - record._timeliness_raw_value_for('birth_datetime').should eq datetime_string + expect(record._timeliness_raw_value_for('birth_datetime')).to eq datetime_string end end @@ -96,7 +96,7 @@ class EmployeeWithCache < ActiveRecord::Base it 'should store raw value' do record.birth_date = date_string = '2010-01-01' - record._timeliness_raw_value_for('birth_date').should eq date_string + expect(record._timeliness_raw_value_for('birth_date')).to eq date_string end end @@ -104,7 +104,7 @@ class EmployeeWithCache < ActiveRecord::Base it 'should store raw value' do record.birth_time = time_string = '12:12' - record._timeliness_raw_value_for('birth_time').should eq time_string + expect(record._timeliness_raw_value_for('birth_time')).to eq time_string end end end @@ -122,13 +122,13 @@ class EmployeeWithParser < ActiveRecord::Base context "for a date column" do it 'should parse a string value' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.birth_date = '2010-01-01' end it 'should parse a invalid string value as nil' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.birth_date = 'not valid' end @@ -136,20 +136,20 @@ class EmployeeWithParser < ActiveRecord::Base it 'should store a Date value after parsing string' do record.birth_date = '2010-01-01' - record.birth_date.should be_kind_of(Date) - record.birth_date.should eq Date.new(2010, 1, 1) + expect(record.birth_date).to be_kind_of(Date) + expect(record.birth_date).to eq Date.new(2010, 1, 1) end end context "for a time column" do it 'should parse a string value' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.birth_time = '12:30' end it 'should parse a invalid string value as nil' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.birth_time = 'not valid' end @@ -157,8 +157,8 @@ class EmployeeWithParser < ActiveRecord::Base it 'should store a Time value after parsing string' do record.birth_time = '12:30' - record.birth_time.should be_kind_of(Time) - record.birth_time.should eq Time.utc(2000, 1, 1, 12, 30) + expect(record.birth_time).to be_kind_of(Time) + expect(record.birth_time).to eq Time.utc(2000, 1, 1, 12, 30) end end @@ -166,13 +166,13 @@ class EmployeeWithParser < ActiveRecord::Base with_config(:default_timezone, 'Australia/Melbourne') it 'should parse a string value' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.birth_datetime = '2010-01-01 12:00' end it 'should parse a invalid string value as nil' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.birth_datetime = 'not valid' end @@ -180,13 +180,13 @@ class EmployeeWithParser < ActiveRecord::Base it 'should parse string into Time value' do record.birth_datetime = '2010-01-01 12:00' - record.birth_datetime.should be_kind_of(Time) + expect(record.birth_datetime).to be_kind_of(Time) end it 'should parse string as current timezone' do record.birth_datetime = '2010-06-01 12:00' - record.birth_datetime.utc_offset.should eq Time.zone.utc_offset + expect(record.birth_datetime.utc_offset).to eq Time.zone.utc_offset end end end @@ -196,10 +196,10 @@ class EmployeeWithParser < ActiveRecord::Base it 'should clear cache value' do record = Employee.create! record.birth_date = '2010-01-01' - + record.reload - record._timeliness_raw_value_for('birth_date').should be_nil + expect(record._timeliness_raw_value_for('birth_date')).to be_nil end end @@ -207,13 +207,13 @@ class EmployeeWithParser < ActiveRecord::Base let(:record) { Employee.new } it 'should be defined on class if ORM supports it' do - record.should respond_to(:birth_datetime_before_type_cast) + expect(record).to respond_to(:birth_datetime_before_type_cast) end it 'should return original value' do record.birth_datetime = date_string = '2010-01-01' - record.birth_datetime_before_type_cast.should eq date_string + expect(record.birth_datetime_before_type_cast).to eq date_string end it 'should return attribute if no attribute assignment has been made' do @@ -221,7 +221,7 @@ class EmployeeWithParser < ActiveRecord::Base Employee.create(:birth_datetime => datetime) record = Employee.last - record.birth_datetime_before_type_cast.should match(/#{datetime.utc.to_s[0...-4]}/) + expect(record.birth_datetime_before_type_cast).to match(/#{datetime.utc.to_s[0...-4]}/) end context "with plugin parser" do @@ -230,7 +230,7 @@ class EmployeeWithParser < ActiveRecord::Base it 'should return original value' do record.birth_datetime = date_string = '2010-01-31' - record.birth_datetime_before_type_cast.should eq date_string + expect(record.birth_datetime_before_type_cast).to eq date_string end end @@ -238,7 +238,7 @@ class EmployeeWithParser < ActiveRecord::Base context "define_attribute_methods" do it "returns a falsy value if the attribute methods have already been generated" do - Employee.define_attribute_methods.should be_false + expect(Employee.define_attribute_methods).to be_falsey end end end diff --git a/spec/validates_timeliness/orm/mongoid_spec.rb b/spec/validates_timeliness/orm/mongoid_spec.rb index 59bb4915..2cab7259 100644 --- a/spec/validates_timeliness/orm/mongoid_spec.rb +++ b/spec/validates_timeliness/orm/mongoid_spec.rb @@ -29,22 +29,22 @@ class Article let(:record) { Article.new } it 'should be defined on the class' do - Article.should respond_to(:validates_date) - Article.should respond_to(:validates_time) - Article.should respond_to(:validates_datetime) + expect(Article).to respond_to(:validates_date) + expect(Article).to respond_to(:validates_time) + expect(Article).to respond_to(:validates_datetime) end it 'should be defined on the instance' do - record.should respond_to(:validates_date) - record.should respond_to(:validates_time) - record.should respond_to(:validates_datetime) + expect(record).to respond_to(:validates_date) + expect(record).to respond_to(:validates_time) + expect(record).to respond_to(:validates_datetime) end it "should validate a valid value string" do record.publish_date = '2012-01-01' record.valid? - record.errors[:publish_date].should be_empty + expect(record.errors[:publish_date]).to be_empty end it "should validate a invalid value string" do @@ -54,19 +54,19 @@ class Article end record.valid? - record.errors[:publish_date].should_not be_empty + expect(record.errors[:publish_date]).not_to be_empty end it "should validate a nil value" do record.publish_date = nil record.valid? - record.errors[:publish_date].should be_empty + expect(record.errors[:publish_date]).to be_empty end end it 'should determine type for attribute' do - Article.timeliness_attribute_type(:publish_date).should == :date + expect(Article.timeliness_attribute_type(:publish_date)).to eq(:date) end context "attribute write method" do @@ -75,7 +75,7 @@ class Article it 'should cache attribute raw value' do record.publish_datetime = date_string = '2010-01-01' - record._timeliness_raw_value_for('publish_datetime').should == date_string + expect(record._timeliness_raw_value_for('publish_datetime')).to eq(date_string) end context "with plugin parser" do @@ -96,13 +96,13 @@ class ArticleWithParser context "for a date column" do it 'should parse a string value' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.publish_date = '2010-01-01' end it 'should parse a invalid string value as nil' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.publish_date = 'not valid' end @@ -110,20 +110,20 @@ class ArticleWithParser it 'should store a Date value after parsing string' do record.publish_date = '2010-01-01' - record.publish_date.should be_kind_of(Date) - record.publish_date.should eq Date.new(2010, 1, 1) + expect(record.publish_date).to be_kind_of(Date) + expect(record.publish_date).to eq Date.new(2010, 1, 1) end end context "for a time column" do it 'should parse a string value' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.publish_time = '12:30' end it 'should parse a invalid string value as nil' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.publish_time = 'not valid' end @@ -131,8 +131,8 @@ class ArticleWithParser it 'should store a Time value after parsing string' do record.publish_time = '12:30' - record.publish_time.should be_kind_of(Time) - record.publish_time.should eq Time.utc(2000, 1, 1, 12, 30) + expect(record.publish_time).to be_kind_of(Time) + expect(record.publish_time).to eq Time.utc(2000, 1, 1, 12, 30) end end @@ -140,13 +140,13 @@ class ArticleWithParser with_config(:default_timezone, 'Australia/Melbourne') it 'should parse a string value' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.publish_datetime = '2010-01-01 12:00' end it 'should parse a invalid string value as nil' do - Timeliness::Parser.should_receive(:parse) + expect(Timeliness::Parser).to receive(:parse) record.publish_datetime = 'not valid' end @@ -154,13 +154,13 @@ class ArticleWithParser it 'should parse string into DateTime value' do record.publish_datetime = '2010-01-01 12:00' - record.publish_datetime.should be_kind_of(DateTime) + expect(record.publish_datetime).to be_kind_of(DateTime) end pending 'should parse string as current timezone' do record.publish_datetime = '2010-06-01 12:00' - record.publish_datetime.utc_offset.should eq Time.zone.utc_offset + expect(record.publish_datetime.utc_offset).to eq Time.zone.utc_offset end end end @@ -171,13 +171,13 @@ class ArticleWithParser record = Article.create! record.publish_date = '2010-01-01' record.reload - record._timeliness_raw_value_for('publish_date').should be_nil + expect(record._timeliness_raw_value_for('publish_date')).to be_nil end end context "before_type_cast method" do it 'should not be defined if ORM does not support it' do - Article.new.should_not respond_to(:publish_datetime_before_type_cast) + expect(Article.new).not_to respond_to(:publish_datetime_before_type_cast) end end end diff --git a/spec/validates_timeliness/validator_spec.rb b/spec/validates_timeliness/validator_spec.rb index 6d03ba1b..009f4349 100644 --- a/spec/validates_timeliness/validator_spec.rb +++ b/spec/validates_timeliness/validator_spec.rb @@ -8,22 +8,22 @@ describe "Model.validates with :timeliness option" do it 'should use plugin validator class' do Person.validates :birth_date, :timeliness => {:is_at => Date.new(2010,1,1), :type => :date} - Person.validators.should have(1).kind_of(ActiveModel::Validations::TimelinessValidator) + expect(Person.validators).to have(1).kind_of(ActiveModel::Validations::TimelinessValidator) invalid!(:birth_date, Date.new(2010,1,2)) valid!(:birth_date, Date.new(2010,1,1)) end it 'should use default to :datetime type' do Person.validates :birth_datetime, :timeliness => {:is_at => Time.mktime(2010,1,1)} - Person.validators.first.type.should == :datetime + expect(Person.validators.first.type).to eq(:datetime) end it 'should add attribute to timeliness attributes set' do - PersonWithShim.timeliness_validated_attributes.should_not include(:birth_time) + expect(PersonWithShim.timeliness_validated_attributes).not_to include(:birth_time) PersonWithShim.validates :birth_time, :timeliness => {:is_at => "12:30"} - PersonWithShim.timeliness_validated_attributes.should include(:birth_time) + expect(PersonWithShim.timeliness_validated_attributes).to include(:birth_time) end end @@ -35,10 +35,10 @@ it 'should not be valid attribute is type cast to nil but raw value is non-nil invalid value' do Person.validates_date :birth_date, :allow_nil => true record = Person.new - record.stub!(:birth_date).and_return(nil) - record.stub!(:_timeliness_raw_value_for).and_return("Not a date") - record.should_not be_valid - record.errors[:birth_date].first.should == 'is not a valid date' + allow(record).to receive(:birth_date).and_return(nil) + allow(record).to receive(:_timeliness_raw_value_for).and_return("Not a date") + expect(record).not_to be_valid + expect(record.errors[:birth_date].first).to eq('is not a valid date') end describe ":allow_nil option" do @@ -60,7 +60,7 @@ p = PersonWithShim.new p.birth_date = 'bogus' - p.should_not be_valid + expect(p).not_to be_valid end end end @@ -84,7 +84,7 @@ p = PersonWithShim.new p.birth_date = 'bogus' - p.should_not be_valid + expect(p).not_to be_valid end end end @@ -94,8 +94,8 @@ it 'should be split option into :on_or_after and :on_or_before values' do on_or_after, on_or_before = Date.new(2010,1,1), Date.new(2010,1,2) Person.validates_date :birth_date, :between => [on_or_after, on_or_before] - Person.validators.first.options[:on_or_after].should == on_or_after - Person.validators.first.options[:on_or_before].should == on_or_before + expect(Person.validators.first.options[:on_or_after]).to eq(on_or_after) + expect(Person.validators.first.options[:on_or_before]).to eq(on_or_before) invalid!(:birth_date, on_or_after - 1, "must be on or after 2010-01-01") invalid!(:birth_date, on_or_before + 1, "must be on or before 2010-01-02") valid!(:birth_date, on_or_after) @@ -107,8 +107,8 @@ it 'should be split option into :on_or_after and :on_or_before values' do on_or_after, on_or_before = Date.new(2010,1,1), Date.new(2010,1,2) Person.validates_date :birth_date, :between => on_or_after..on_or_before - Person.validators.first.options[:on_or_after].should == on_or_after - Person.validators.first.options[:on_or_before].should == on_or_before + expect(Person.validators.first.options[:on_or_after]).to eq(on_or_after) + expect(Person.validators.first.options[:on_or_before]).to eq(on_or_before) invalid!(:birth_date, on_or_after - 1, "must be on or after 2010-01-01") invalid!(:birth_date, on_or_before + 1, "must be on or before 2010-01-02") valid!(:birth_date, on_or_after) @@ -120,8 +120,8 @@ it 'should be split option into :on_or_after and :before values' do on_or_after, before = Date.new(2010,1,1), Date.new(2010,1,3) Person.validates_date :birth_date, :between => on_or_after...before - Person.validators.first.options[:on_or_after].should == on_or_after - Person.validators.first.options[:before].should == before + expect(Person.validators.first.options[:on_or_after]).to eq(on_or_after) + expect(Person.validators.first.options[:before]).to eq(before) invalid!(:birth_date, on_or_after - 1, "must be on or after 2010-01-01") invalid!(:birth_date, before, "must be before 2010-01-03") valid!(:birth_date, on_or_after) @@ -159,13 +159,13 @@ class PersonWithFormatOption it "should be valid when value matches format" do person.birth_date = '11-12-1913' person.valid? - person.errors[:birth_date].should be_empty + expect(person.errors[:birth_date]).to be_empty end it "should not be valid when value does not match format" do person.birth_date = '1913-12-11' person.valid? - person.errors[:birth_date].should include('is not a valid date') + expect(person.errors[:birth_date]).to include('is not a valid date') end end @@ -179,21 +179,21 @@ class PersonWithFormatOption it "should be added when ignore_restriction_errors is false" do with_config(:ignore_restriction_errors, false) do person.valid? - person.errors[:birth_date].first.should match("Error occurred validating birth_date") + expect(person.errors[:birth_date].first).to match("Error occurred validating birth_date") end end it "should not be added when ignore_restriction_errors is true" do with_config(:ignore_restriction_errors, true) do person.valid? - person.errors[:birth_date].should be_empty + expect(person.errors[:birth_date]).to be_empty end end it 'should exit on first error' do with_config(:ignore_restriction_errors, false) do person.valid? - person.errors[:birth_date].should have(1).items + expect(person.errors[:birth_date]).to have(1).items end end end @@ -202,17 +202,17 @@ class PersonWithFormatOption describe "default" do it 'should format date error value as yyyy-mm-dd' do validator = ValidatesTimeliness::Validator.new(:attributes => [:birth_date], :type => :date) - validator.format_error_value(Date.new(2010,1,1)).should == '2010-01-01' + expect(validator.format_error_value(Date.new(2010,1,1))).to eq('2010-01-01') end it 'should format time error value as hh:nn:ss' do validator = ValidatesTimeliness::Validator.new(:attributes => [:birth_time], :type => :time) - validator.format_error_value(Time.mktime(2010,1,1,12,34,56)).should == '12:34:56' + expect(validator.format_error_value(Time.mktime(2010,1,1,12,34,56))).to eq('12:34:56') end it 'should format datetime error value as yyyy-mm-dd hh:nn:ss' do validator = ValidatesTimeliness::Validator.new(:attributes => [:birth_datetime], :type => :datetime) - validator.format_error_value(Time.mktime(2010,1,1,12,34,56)).should == '2010-01-01 12:34:56' + expect(validator.format_error_value(Time.mktime(2010,1,1,12,34,56))).to eq('2010-01-01 12:34:56') end end @@ -223,7 +223,7 @@ class PersonWithFormatOption it 'should use the default format for the type' do validator = ValidatesTimeliness::Validator.new(:attributes => [:birth_date], :type => :date) - validator.format_error_value(Date.new(2010,1,1)).should == '2010-01-01' + expect(validator.format_error_value(Date.new(2010,1,1))).to eq('2010-01-01') end after :all do diff --git a/spec/validates_timeliness_spec.rb b/spec/validates_timeliness_spec.rb index 7a686505..5a402a1b 100644 --- a/spec/validates_timeliness_spec.rb +++ b/spec/validates_timeliness_spec.rb @@ -3,39 +3,39 @@ describe ValidatesTimeliness do it 'should alias use_euro_formats to remove_us_formats on Timeliness gem' do - Timeliness.should respond_to(:remove_us_formats) + expect(Timeliness).to respond_to(:remove_us_formats) end it 'should alias to date_for_time_type to dummy_date_for_time_type on Timeliness gem' do - Timeliness.should respond_to(:dummy_date_for_time_type) + expect(Timeliness).to respond_to(:dummy_date_for_time_type) end describe "config" do it 'should delegate default_timezone to Timeliness gem' do - Timeliness.should_receive(:default_timezone=) + expect(Timeliness).to receive(:default_timezone=) ValidatesTimeliness.default_timezone = :utc end it 'should delegate dummy_date_for_time_type to Timeliness gem' do - Timeliness.should_receive(:dummy_date_for_time_type) - Timeliness.should_receive(:dummy_date_for_time_type=) + expect(Timeliness).to receive(:dummy_date_for_time_type) + expect(Timeliness).to receive(:dummy_date_for_time_type=) array = ValidatesTimeliness.dummy_date_for_time_type ValidatesTimeliness.dummy_date_for_time_type = array end context "parser" do it 'should delegate add_formats to Timeliness gem' do - Timeliness.should_receive(:add_formats) + expect(Timeliness).to receive(:add_formats) ValidatesTimeliness.parser.add_formats end it 'should delegate remove_formats to Timeliness gem' do - Timeliness.should_receive(:remove_formats) + expect(Timeliness).to receive(:remove_formats) ValidatesTimeliness.parser.remove_formats end it 'should delegate remove_us_formats to Timeliness gem' do - Timeliness.should_receive(:remove_us_formats) + expect(Timeliness).to receive(:remove_us_formats) ValidatesTimeliness.parser.remove_us_formats end end diff --git a/validates_timeliness.gemspec b/validates_timeliness.gemspec index 26237a2c..320b06b2 100644 --- a/validates_timeliness.gemspec +++ b/validates_timeliness.gemspec @@ -3,18 +3,23 @@ $:.push File.expand_path("../lib", __FILE__) require "validates_timeliness/version" Gem::Specification.new do |s| - s.name = "validates_timeliness" + s.name = "jc-validates_timeliness" s.version = ValidatesTimeliness::VERSION - s.authors = ["Adam Meehan"] + s.authors = ["Adam Meehan", "John Carney"] s.summary = %q{Date and time validation plugin for Rails which allows custom formats} s.description = %q{Adds validation methods to ActiveModel for validating dates and times. Works with multiple ORMS.} s.email = %q{adam.meehan@gmail.com} - s.homepage = %q{http://github.com/adzap/validates_timeliness} + s.homepage = %q{http://github.com/johncarney/validates_timeliness} s.require_paths = ["lib"] - s.files = `git ls-files`.split("\n") - %w{ .gitignore .rspec Gemfile Gemfile.lock autotest/discover.rb Appraisals Travis.yml } - Dir['gemsfiles/*'] + s.files = `git ls-files`.split("\n") - %w{ .gitignore .rspec Gemfile Gemfile.lock autotest/discover.rb Appraisals .travis.yml .coveralls.yml } - Dir['gemfiles/*'] s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") - s.extra_rdoc_files = ["README.rdoc", "CHANGELOG.rdoc", "LICENSE"] + s.extra_rdoc_files = ["CHANGELOG.rdoc", "LICENSE"] s.add_runtime_dependency(%q, ["~> 0.3.7"]) + + s.add_development_dependency "coveralls" + s.add_development_dependency "rspec", "~> 3.0" + s.add_development_dependency "rspec-rails", "~> 3.0" + s.add_development_dependency "rspec-collection_matchers" end