使用rspec(ruby项目)编写文件验证规范



这两个测试用例失败,

describe 'validations' do
it { should validate_presence_of :file }
it { should validate_presence_of :save_path }
end

这就是我正在测试的类,

class ConvertFileToPdf < Base
attr_accessor(
:file,
:save_path
)
validates_presence_of(
:file,
:save_path
)
def path
'/Convert/ConvertFileToPdf'
end
def save_path
@save_path ||= File.join(File.dirname(file), "#{File.basename(file, ".*")}.pdf")
end
def call_api
client.multipart_post(
path,
file_name: File.basename(file),
file: File.open(file, 'rb'),
) do |request|
download(request, save_path)
end
end
end

失败测试用例

在执行save_path的存在性检查时,将调用相应的读取器方法。在此过程中,如果file没有填充有效值,则来自File.dirname的合成将失败。

您可能应该在save_path方法中添加一个保护子句:

def save_path
return if file.nil?
@save_path ||= File.join(File.dirname(file), "#{File.basename(file, ".*")}.pdf")
end

最新更新