Last active
March 23, 2021 14:06
-
-
Save searls/c29842f16806ac5d5ff65771438c6e2a to your computer and use it in GitHub Desktop.
Approach to testing validations simply
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
require "test_helper" | |
class AttestationTest < ActiveSupport::TestCase | |
def test_validate_not_already_attested | |
user = User.new | |
Attestation.create!(user: user, date: Date.civil(2021, 2, 28)) | |
assert_validation :already_attested, Attestation.new(user: user, date: Date.civil(2021, 2, 16)) | |
assert_validation :already_attested, Attestation.new(user: user, date: Date.civil(2021, 2, 28)) | |
refute_validation :already_attested, Attestation.new(user: user, date: Date.civil(2021, 3, 15)) | |
end | |
private | |
# Requires custom validation errors be added in the model using the full API: | |
# errors.add(:base, :already_attested, message: "fa la la") | |
def assert_validation(validation_type, model, attr = :base) | |
model.valid? | |
assert model.errors.added?(attr, validation_type), "Expected #{model.inspect} to have error #{validation_type} added to attr #{attr}, but it did not" | |
end | |
def refute_validation(validation_type, model, attr = :base) | |
model.valid? | |
refute model.errors.added?(attr, validation_type), "Expected #{model.inspect} not to have error #{validation_type} added to attr #{attr}, but it did" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment