Created
July 30, 2014 14:11
-
-
Save zapo/959df1e7c54283335db7 to your computer and use it in GitHub Desktop.
Validations test helper
This file contains 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
module Helpers | |
module Validations | |
private | |
def assert_valid_url url | |
assert_match URI::regexp(%w(http https)), url, "\"#{url}\" isn't a valid URL" | |
end | |
def assert_validated_presence object, attribute, success_val = "not blank", expected_msg = :blank | |
assert_validated object, attribute, | |
:success_val => success_val, | |
:failing_val => nil, | |
:expected_msg => expected_msg | |
end | |
def assert_validated_url object, attribute, expected_msg = :invalid_url | |
assert_validated object, attribute, | |
:failing_val => "1234", | |
:success_val => "http://www.google.ca", | |
:expected_msg => expected_msg | |
end | |
def assert_validated object, attribute, options = {} | |
failing_val = options.fetch(:failing_val) | |
success_val = options.fetch(:success_val) | |
expected_msg = options.fetch(:expected_msg) | |
attribute = attribute.to_sym | |
get_expected_msg = lambda { |msg| | |
case expected_msg | |
when Symbol | |
object.errors.generate_message(attribute, expected_msg) | |
when Proc | |
msg.call(object, attribute) | |
when String | |
#noop | |
else | |
raise ArgumentError, "Invalid expected_msg #{msg}" | |
end | |
} | |
expected_msg = get_expected_msg.call(expected_msg) | |
write_attribute(object, attribute, failing_val) | |
assert object.invalid? | |
assert_includes object.errors[attribute], expected_msg | |
write_attribute(object, attribute, success_val) | |
object.valid? | |
refute_includes object.errors[attribute], expected_msg | |
end | |
def read_attribute object, attribute | |
object.send(:"#{attribute}") | |
end | |
def write_attribute object, attribute, val | |
object.send(:"#{attribute}=", val) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment