水豚在 RSpec/Rails 测试中找不到要附加的文件

Capybara can't find a file to attach in an RSpec/Rails test

我正在使用 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="&#x2713;" /><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 的情况下尝试过它,并且最初将它放在 public 文件夹中,我在其中尝试了 Rails.root + /public/instagram-logo.jp,然后只是 /public/instagram-logo.jpg,最后是 instagram-logo.jp。不确定问题是文件路径还是更远的地方。在 web_helper.

中也尝试过 attach_file("image"...

非常感谢任何帮助!

当您传递像 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>