Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stratigos/5e0e704b250ab49cd1fa55363d9a3068 to your computer and use it in GitHub Desktop.
Save stratigos/5e0e704b250ab49cd1fa55363d9a3068 to your computer and use it in GitHub Desktop.
RSpec Validates Numericality of Active Record Model with Shoulda Matchers
# Shared specs for models with the `:validates_numericality_of` validators.
# Usage: pass a hash of each of the symbolized names of each options for the
# numericality validator. If the option has a value with which to evaluate
# against, add it as the value of that option hash name.
# E.g.:
# `it_behaves_like :validates_numericality_model, :numeric_attr, { greater_than_or_equal_to: 0, only_integer: true }`
RSpec.shared_examples :validates_numericality_model do |attribute_name, options|
it { is_expected.to validate_numericality_of(attribute_name) }
if options.key? :greater_than_or_equal_to
it { is_expected.to allow_value(options[:greater_than_or_equal_to]).for(attribute_name) }
it { is_expected.not_to allow_value(options[:greater_than_or_equal_to].to_i - 1).for(attribute_name) }
end
if options.key? :less_than_or_equal_to
it { is_expected.to allow_value(options[:less_than_or_equal_to]).for(attribute_name) }
it { is_expected.not_to allow_value(options[:less_than_or_equal_to].to_i + 1).for(attribute_name) }
end
it { is_expected.not_to allow_value(0.5).for(attribute_name) } if options[:only_integer]
it { is_expected.to allow_value(nil).for(attribute_name) } if options[:allow_nil]
end
@stratigos
Copy link
Author

This is for expressing the full specification of a data model's attribute when there are many conditions regarding the numerical value of said attr.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment