diff --git a/lib/dor/datastreams/content_metadata_ds.rb b/lib/dor/datastreams/content_metadata_ds.rb
index 577cf056..7347d427 100644
--- a/lib/dor/datastreams/content_metadata_ds.rb
+++ b/lib/dor/datastreams/content_metadata_ds.rb
@@ -174,7 +174,7 @@ def add_file(file, resource_name)
def add_virtual_resource(child_druid, child_resource)
# create a virtual resource element with attributes linked to the child and omit label
ng_xml_will_change!
- sequence_max = ng_xml.search('//resource').map { |node| node[:sequence].to_i }.max
+ sequence_max = ng_xml.search('//resource').map { |node| node[:sequence].to_i }.max || 0
resource = Nokogiri::XML::Element.new('resource', ng_xml)
resource[:sequence] = sequence_max + 1
resource[:id] = "#{pid.gsub(/^druid:/, '')}_#{resource[:sequence]}"
diff --git a/spec/datastreams/content_metadata_ds_spec.rb b/spec/datastreams/content_metadata_ds_spec.rb
index c1db5f1f..3c4ba81e 100644
--- a/spec/datastreams/content_metadata_ds_spec.rb
+++ b/spec/datastreams/content_metadata_ds_spec.rb
@@ -321,5 +321,48 @@
expect(externalFile[0]['mimetype']).to eq('image/tiff')
expect(externalFile[1]['mimetype']).to eq('image/jp2')
end
+
+ it 'adds a virtual resource to parent when parent has no resources in existing contentMetadata' do
+ item = instantiate_fixture('druid:ab123cd4567', Dor::Item)
+ item.contentMetadata.content = '
+ '
+ allow(Dor).to receive(:find).and_return(item)
+
+ child_druid = 'bb273jy3359'
+ child_resource = Nokogiri::XML('
+
+
+
+ 65fad5e9dbaaef1130e500f6472a7200
+ 374d1b71522acf10bbe9fff6af5f50dd5de3022c
+
+
+
+ ').root
+
+ item.contentMetadata.add_virtual_resource(child_druid, child_resource)
+ # parent contentMetadata is updated
+ expect(item.contentMetadata).to be_changed
+ nodes = item.contentMetadata.ng_xml.search('//resource[@id=\'ab123cd4567_1\']')
+ expect(nodes.length).to eq(1)
+ node = nodes.first
+ expect(node['id']).to eq('ab123cd4567_1')
+ expect(node['type']).to eq('image')
+ expect(node['sequence']).to eq('1')
+
+ expect(nodes.search('label').length).to eq(0)
+
+ externalFile = nodes.search('externalFile')
+ expect(externalFile.length).to eq(1)
+ expect(externalFile.first['objectId']).to eq('bb273jy3359')
+ expect(externalFile.first['resourceId']).to eq('bb273jy3359_1')
+ expect(externalFile.first['fileId']).to eq('00006672_0007.jp2')
+ expect(externalFile.first['mimetype']).to eq('image/jp2')
+
+ relationship = nodes.search('relationship')
+ expect(relationship.length).to eq(1)
+ expect(relationship.first['type']).to eq('alsoAvailableAs')
+ expect(relationship.first['objectId']).to eq('bb273jy3359')
+ end
end
end