我使用Capybara / RSpec在Rails 5应用程序中编写功能测试,以检查我网站上的图像上传。我收到了这个错误:
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
我的测试是 要求' rails_helper' 要求' 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
网络助手:
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
观点:
<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>
从视图中编译的HTML:
<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>
该文件肯定在该文件路径中。我在没有Rails.root
的情况下尝试了它,并且最初在我尝试Rails.root + /public/instagram-logo.jp
的公共文件夹中进行了尝试,只是/public/instagram-logo.jpg
,最后是instagram-logo.jp
。不确定问题是文件路径还是沿着这条线走得更远。还尝试了web_helper中的attach_file("image"...
。
非常感谢任何帮助!
答案 0 :(得分:2)
当您通过像Rails.root + '/app/assets/images/instagram-logo.jpg'
这样的绝对路径时,Rails.root
将被忽略。试试Rails.root + 'app/assets/images/instagram-logo.jpg'
,看看会发生什么。
同时检查文件是否真的存在:
File.exist?(Rails.root + 'app/assets/images/instagram-logo.jpg')
(因为这是CapyBara https://github.com/teamcapybara/capybara/blob/3a2c5d21e756460d388995aa9698c4bc8c6ba49d/lib/capybara/node/actions.rb#L238抛出的错误)
仅供参考:这是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>