Created
April 19, 2018 16:54
-
-
Save stratigos/5e0e704b250ab49cd1fa55363d9a3068 to your computer and use it in GitHub Desktop.
RSpec Validates Numericality of Active Record Model with Shoulda Matchers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.