From ef1c8bd8b64f18ba70cfba957a914abd70614fea Mon Sep 17 00:00:00 2001 From: Geoff Wilson Date: Thu, 5 Sep 2024 12:40:05 -0400 Subject: [PATCH] Add validations and unit test to Domain model --- app/models/domain.rb | 2 ++ test/models/domain_test.rb | 40 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 test/models/domain_test.rb diff --git a/app/models/domain.rb b/app/models/domain.rb index 078f297..b0bd65c 100644 --- a/app/models/domain.rb +++ b/app/models/domain.rb @@ -2,6 +2,8 @@ class Domain < ApplicationRecord serialize :groups, coder: YAML, type: Array before_save :clean_groups + validates :fqdn, :owner, presence: true + def clean_groups self.groups = groups.sort.uniq end diff --git a/test/models/domain_test.rb b/test/models/domain_test.rb new file mode 100644 index 0000000..0a9192f --- /dev/null +++ b/test/models/domain_test.rb @@ -0,0 +1,40 @@ +# test/models/cert_issue_request_test.rb +require "test_helper" + +class DomainTest < ActiveSupport::TestCase + def setup + @attributes = { + fqdn: "example4.com", + owner: "john.doe@example.com", + } + @domain = Domain.new(@attributes) + end + + test "#new should set attributes from attributes argument" do + @attributes.each do |key, value| + assert_equal value, @domain.send(key), "Attribute #{key} was not set correctly" + end + end + + test "#valid? should be valid with valid attributes" do + assert @domain.valid? + end + + test "#valid? should require an fqdn" do + @domain.fqdn = nil + assert_not @domain.valid? + assert_includes @domain.errors[:fqdn], "can't be blank" + end + + test "#valid? should require an owner" do + @domain.owner = nil + assert_not @domain.valid? + assert_includes @domain.errors[:owner], "can't be blank" + end + + test "before_save should sort and dedupe groups" do + @domain.groups = [ "two", "two", "one" ] + @domain.save + assert_equal [ "one", "two" ], @domain.groups + end +end