I'm writing unit tests for my Rails 5 app using Rspec and Capybara, and I'm currently stuck trying to test the ability to rename files uploaded to my controller. The app seems to work flawlessly: I have a Documents controller with an attached File thanks to Paperclip, and a view that allows the user to edit the filename (without the extension), so when the user clicks on the Save button, the controller uses FileUtils to "rename" the file:
@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))
this has been thoroughly tested by several teammates and it doesn't break so far. However, the problem comes when trying to run my unit test:
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
And then, when I run the test, I get the following error:
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
This is not a Rails error, but a Puma one: https://i.sstatic.net/7dAxT.png
Any help will be appreciated.
I'm guessing /home/moyarzun/GarageLabs/lexgo/public/system/documents/files/000/000/001/original/test_file.docx
is actually a soft link to a file elsewhere in the system, and that a link to the same file named /home/moyarzun/GarageLabs/lexgo/public/system/documents/files/000/000/001/original/edited_filename.docx
already exists when you're running the test (because the tests aren't clearing out the links created each time it's run). If you try and move a link to another another link which is already linked to the same file you'll get the 'same file` argument error. You want to make sure you clean up files from tests when the tests complete (or before running the tests).