diff --git a/lib/seek/samples/sample_type_editing_constraints.rb b/lib/seek/samples/sample_type_editing_constraints.rb index c1a310208c..9f599e503e 100644 --- a/lib/seek/samples/sample_type_editing_constraints.rb +++ b/lib/seek/samples/sample_type_editing_constraints.rb @@ -21,7 +21,7 @@ def samples? # if attr is nil, indicates a new attribute. required is not allowed if there are already samples def allow_required?(attr) if attr.is_a?(SampleAttribute) - return true if attr.new_record? + return true if attr.new_record? && @sample_type.new_record? return false if inherited?(attr) attr = attr.accessor_name diff --git a/test/functional/sample_types_controller_test.rb b/test/functional/sample_types_controller_test.rb index 4cef1f1178..59fca0173c 100644 --- a/test/functional/sample_types_controller_test.rb +++ b/test/functional/sample_types_controller_test.rb @@ -775,16 +775,28 @@ class SampleTypesControllerTest < ActionController::TestCase get :edit, params: { id: sample_type.id } assert_response :success assert_select 'a#add-attribute', count: 1 - assert_difference('SampleAttribute.count') do - put :update, params: { id: sample_type.id, sample_type: { + + # Should be able to add an optional new attribute to a sample type with samples + assert_difference('SampleAttribute.count', 1) do + patch :update, params: { id: sample_type.id, sample_type: { sample_attributes_attributes: { - '1': { title: 'new attribute', sample_attribute_type_id: @string_type.id } + '1': { title: 'new optional attribute', sample_attribute_type_id: @string_type.id, required: '0' } } } } end assert_redirected_to sample_type_path(sample_type) sample_type.reload - assert_equal 'new attribute', sample_type.sample_attributes.last.title + assert_equal 'new optional attribute', sample_type.sample_attributes.last.title + + # Should not be able to add a mandatory new attribute to a sample type with samples + assert_no_difference('SampleAttribute.count') do + patch :update, params: { id: sample_type.id, sample_type: { + sample_attributes_attributes: { + '2': { title: 'new mandatory attribute', sample_attribute_type_id: @string_type.id, required: '1' } + } + } } + end + end test 'change attribute name' do