class **ConverterFile**
attr_accessor :old_file
SUPPORT_IMAGE_FORMAT = %w[png jpg jpeg pdf].freeze
def initialize(old_file)
@old_file = old_file
end
def to_image_type(file_format)
raise 'format not support' if file_format.blank? || SUPPORT_IMAGE_FORMAT.exclude?(file_format)
return old_file if File.extname(@old_file) == ".#{file_format}"
converted_file = MiniMagick::Image.open(@old_file.path)
converted_file.format(file_format)
File.open(converted_file.path)
rescue StandardError => e
nil
end
end
describe '#to_image_type' do
let(:png_file) { File.open(Rails.root.join('spec/support/files/logo.png')) }
context 'when convert to jpg file' do
it 'convert png file to jpg successfuly' do
new_file = described_class.new(png_file).to_image_type('jpg')
expect(File.extname(new_file)).to eq('.jpg')
end
end
end
error-in-gitlab-ci-cd
我很困惑,因为我试着在环境开发本地运行规范是通过的,但每次gitlab ci/cd错误。我认为错误是关于参考文件丢失,不确定。
错误提示使用nil
参数调用File.extname
:
File.extname(nil)
#=> TypeError: no implicit conversion of nil into String
表示new_file
必须是nil
。
这意味着described_class.new(png_file).to_image_type('jpg')
必须返回nil
。
为什么会发生这种情况?嗯,如果不仔细看看CI设置,我很难确定,但我对这部分代码非常怀疑:
rescue StandardError => e
nil
end
你的方法正在默默地吞下错误,并返回nil
。一般来说,这似乎不是一个好主意,它可能是隐藏了测试失败的真正原因!
我的怀疑是您没有将文件'spec/support/files/logo.png'
提交到源代码管理。因此,测试在本地通过,但在CI上失败,因为该文件不存在。
我认为当不存在的文件被打开时,会引发一个异常,但是您正在捕获异常并返回nil
——这导致了这个更令人困惑的测试失败消息。