Skip to content

Instantly share code, notes, and snippets.

@zapo
Created July 30, 2014 14:11
Show Gist options
  • Save zapo/959df1e7c54283335db7 to your computer and use it in GitHub Desktop.
Save zapo/959df1e7c54283335db7 to your computer and use it in GitHub Desktop.

Revisions

  1. zapo created this gist Jul 30, 2014.
    67 changes: 67 additions & 0 deletions validations.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@
    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