Skip to content

Instantly share code, notes, and snippets.

@searls
Last active March 23, 2021 14:06
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 searls/c29842f16806ac5d5ff65771438c6e2a to your computer and use it in GitHub Desktop.
Save searls/c29842f16806ac5d5ff65771438c6e2a to your computer and use it in GitHub Desktop.
Approach to testing validations simply
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