Reputation: 17
I'm using Capybara/RSpec to write a feature test in a Rails 5 app to check the uploading of images on my site. I am getting this error:
1) Photos user adds a photo
Failure/Error: attach_file("photo[image]", '/app/assets/images/instagram-logo.jpg')
Capybara::FileNotFound:
cannot attach file, /app/assets/images/instagram-logo.jpg does not exist
My test is require 'rails_helper' require 'web_helpers'
RSpec.feature "Photos", type: :feature do
scenario "user adds a photo", :type => :feature do
add_photo
page.should have_content("Instagram Logo")
expect(page).to have_css("img[src*='instagram-logo.jpg']")
end
end
Web helper:
def add_photo
sign_up
visit "/photos"
click_button "New Photo"
fill_in "Title", :with => "Instagram Logo"
attach_file("photo[image]", Rails.root + '/app/assets/images/instagram-logo.jpg')
end
The view:
<div class="field">
<%= form.label :title %>
<%= form.text_field :title, id: :photo_title %>
</div>
<div class="field">
<%= form.label :image %>
<%= form.file_field :image, id: :photo_title %>
</div>
<div class="actions">
<%= form.submit %>
</div>
The HTML compiled from the view:
<form enctype="multipart/form-data" action="/photos" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="igZ4MndDfIQdZOmdiPxKu14bTIkAQTeKG+hwq0E6swKuskkkiCFwEVkarMgS26lc83z1eB/QyuQtnfFLRyuLWQ==" />
<div class="field">
<label for="photo_title">Title</label>
<input id="photo_title" type="text" name="photo[title]" />
</div>
<div class="field">
<label for="photo_image">Image</label>
<input id="photo_title" type="file" name="photo[image]" />
</div>
<div class="actions">
<input type="submit" name="commit" value="Create Photo" data-disable-with="Create Photo" />
</div>
</form>
The file is definitely in that filepath. I have tried it without the Rails.root
, and also originally had it in the public folder where I tried Rails.root + /public/instagram-logo.jp
and simply /public/instagram-logo.jpg
and finally instagram-logo.jp
. Not sure if the issue is the filepath or perhaps a bit further back along the line. Have also tried attach_file("image"...
in the web_helper.
Any help much appreciated!
Upvotes: 1
Views: 1350
Reputation: 3407
When you pass an abolute path like Rails.root + '/app/assets/images/instagram-logo.jpg'
, Rails.root
will be ignored. Try Rails.root + 'app/assets/images/instagram-logo.jpg'
and see what happens.
Also check if the File really exists with:
File.exist?(Rails.root + 'app/assets/images/instagram-logo.jpg')
(Since this is the error thrown by CapyBara https://github.com/teamcapybara/capybara/blob/3a2c5d21e756460d388995aa9698c4bc8c6ba49d/lib/capybara/node/actions.rb#L238)
FYI: This is a behaviour of Pathname
:
pry(main)> Pathname.new("/this/is/my/root") + "/plus/absolute"
=> #<Pathname:/plus/absolute>
pry(main)> Pathname.new("/this/is/my/root") + "plus/relative"
=> #<Pathname:/this/is/my/root/plus/relative>
Upvotes: 3