validations_context_test.rb 2.6 KB
Newer Older
1 2
# frozen_string_literal: true

3
require "cases/helper"
4

5
require "models/topic"
6

7
class ValidationsContextTest < ActiveModel::TestCase
8
  def teardown
9
    Topic.clear_validators!
10 11 12
  end

  ERROR_MESSAGE = "Validation error from validator"
13
  ANOTHER_ERROR_MESSAGE = "Another validation error from validator"
14 15 16 17 18 19 20

  class ValidatorThatAddsErrors < ActiveModel::Validator
    def validate(record)
      record.errors[:base] << ERROR_MESSAGE
    end
  end

21 22 23 24 25 26
  class AnotherValidatorThatAddsErrors < ActiveModel::Validator
    def validate(record)
      record.errors[:base] << ANOTHER_ERROR_MESSAGE
    end
  end

27
  test "with a class that adds errors on create and validating a new model with no arguments" do
28
    Topic.validates_with(ValidatorThatAddsErrors, on: :create)
29
    topic = Topic.new
30
    assert topic.valid?, "Validation doesn't run on valid? if 'on' is set to create"
31 32 33
  end

  test "with a class that adds errors on update and validating a new model" do
34
    Topic.validates_with(ValidatorThatAddsErrors, on: :update)
35 36 37 38 39
    topic = Topic.new
    assert topic.valid?(:create), "Validation doesn't run on create if 'on' is set to update"
  end

  test "with a class that adds errors on create and validating a new model" do
40
    Topic.validates_with(ValidatorThatAddsErrors, on: :create)
41 42
    topic = Topic.new
    assert topic.invalid?(:create), "Validation does run on create if 'on' is set to create"
43
    assert_includes topic.errors[:base], ERROR_MESSAGE
44
  end
45 46 47

  test "with a class that adds errors on multiple contexts and validating a new model" do
    Topic.validates_with(ValidatorThatAddsErrors, on: [:context1, :context2])
48

49
    topic = Topic.new
50 51 52
    assert topic.valid?, "Validation ran with no context given when 'on' is set to context1 and context2"

    assert topic.invalid?(:context1), "Validation did not run on context1 when 'on' is set to context1 and context2"
53
    assert_includes topic.errors[:base], ERROR_MESSAGE
54 55

    assert topic.invalid?(:context2), "Validation did not run on context2 when 'on' is set to context1 and context2"
56
    assert_includes topic.errors[:base], ERROR_MESSAGE
57
  end
58 59 60 61 62 63 64 65 66

  test "with a class that validating a model for a multiple contexts" do
    Topic.validates_with(ValidatorThatAddsErrors, on: :context1)
    Topic.validates_with(AnotherValidatorThatAddsErrors, on: :context2)

    topic = Topic.new
    assert topic.valid?, "Validation ran with no context given when 'on' is set to context1 and context2"

    assert topic.invalid?([:context1, :context2]), "Validation did not run on context1 when 'on' is set to context1 and context2"
67 68
    assert_includes topic.errors[:base], ERROR_MESSAGE
    assert_includes topic.errors[:base], ANOTHER_ERROR_MESSAGE
69
  end
70
end