首页 > 解决方案 > Puma:使用 FileUtils.mv() 测试文件名编辑时出现“相同文件”错误

问题描述

我正在使用 Rspec 和 Capybara 为我的 Rails 5 应用程序编写单元测试,我目前正试图测试重命名上传到我的控制器的文件的能力。该应用程序似乎可以完美运行:感谢 Paperclip,我有一个带有附加文件的 Documents 控制器,以及一个允许用户编辑文件名(不带扩展名)的视图,因此当用户单击“保存”按钮时,控制器使用FileUtils 来“重命名”文件:

@document = Document.find(params[:id])
path = @document.file.path
@document.file_file_name = params[:document][:filename] + '.' + params[:document][:extension]
@document.project_id = params[:document][:project_id]
@document.user_id = params[:document][:user_id]
FileUtils.mv(path, File.join(File.dirname(path), @document.file_file_name))

这已经被几个队友彻底测试过,到目前为止还没有打破。但是,在尝试运行我的单元测试时出现了问题:

RSpec.describe "documents/edit.html.erb", type: :feature do

# Creating user, document, and related models...

  it "edits a file as Admin" do
    sign_in @user_admin
    visit edit_document_path(@document)
    find('#document_filename').set('edited_filename')
    find("input[type=submit][value='Save']").click
    expect(page).to have_content("edited_filename.docx")
  end
end

然后,当我运行测试时,我收到以下错误:

Failures:

1) documents/edit.html.erb edits a file as Admin
   Failure/Error: FileUtils.mv(path, File.join(File.dirname(path), @document.file_file_name))

 ArgumentError:
   same file: /home/moyarzun/GarageLabs/lexgo/public/system/documents/files/000/000/001/original/test_file.docx and /home/moyarzun/GarageLabs/lexgo/public/system/documents/files/000/000/001/original/edited_filename.docx

这不是 Rails 错误,而是 Puma 错误:https ://i.stack.imgur.com/7dAxT.png

任何帮助将不胜感激。

标签: ruby-on-railscapybararspec-railsfileutils

解决方案


我猜 /home/moyarzun/GarageLabs/lexgo/public/system/documents/files/000/000/001/original/test_file.docx实际上是指向系统其他地方的文件的软链接,并且/home/moyarzun/GarageLabs/lexgo/public/system/documents/files/000/000/001/original/edited_filename.docx在运行测试时已经存在指向同一个文件的链接(因为测试并没有清除每次创建的链接)跑)。如果您尝试将链接移动到已链接到同一文件的另一个链接,您将收到“相同文件”参数错误。您要确保在测试完成时(或在运行测试之前)清除测试中的文件。


推荐阅读