Skip to content

Commit

Permalink
Add validation for item_type
Browse files Browse the repository at this point in the history
This ensures that item_types only have values that are defined in the
config, as well as ensures they cannot be changed once persisted.
  • Loading branch information
pezholio committed Jun 4, 2024
1 parent 252dcf6 commit f683df6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
10 changes: 10 additions & 0 deletions app/models/object_store/item.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ class Item < Edition

after_initialize :add_field_accessors

validates :item_type, presence: true, on: :create
validate :item_type_cannot_change
validates :item_type, inclusion: { in: ObjectStore.item_types }

def summary_required?
false
end
Expand All @@ -29,5 +33,11 @@ def add_field_accessors
rescue UnknownItemType
# Ignored
end

def item_type_cannot_change
if persisted? && item_type_changed?
errors.add :item_type, "cannot be changed after creation"
end
end
end
end
22 changes: 22 additions & 0 deletions test/unit/app/models/object_store/item_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,26 @@ class ObjectStore::ItemTest < ActiveSupport::TestCase
test "#previously_published returns false" do
assert_equal @item.previously_published, false
end

test "item_type is required" do
item = build(:object_store_item, item_type: nil)
assert_not item.valid?
assert item.errors[:item_type].any?
end

test "item_type cannot be changed" do
@item.email_address = "[email protected]"
@item.save!

@item.item_type = "foo"
assert_not @item.valid?
assert @item.errors[:item_type].include?("cannot be changed after creation")
end

test "item_type must be valid" do
item = build(:object_store_item, item_type: "banana")

assert_not item.valid?
assert item.errors[:item_type].any?
end
end

0 comments on commit f683df6

Please sign in to comment.