user10358924
user10358924

Reputation:

I want to do Image upload test(feature spec)

I want to test Image uploader.

My error is

Failure/Error: attach_file "picture", "#{Rails.root}/spec/files/attachment.jpg"

     Capybara::ElementNotFound:
       Unable to find visible file field "picture" that is not disabled

My code is (features/posts_spec.rb)

scenario "Access posting screen and post" do
   sign_in user
    visit new_post_path
    expect(page).to have_current_path(new_post_path)
    fill_in "share impression", with: "hogehoge"
    attach_file "picture", "#{Rails.root}/spec/files/attachment.jpg"
    click_on "post"
    expect(page).to have_current_path(posts_path)
  end

(posts/new.html.erb)

 <%= form_with(model: post, local: true) do |f| %>
   <div class="mb-3">
    <%= f.label :picture %>
    <%= f.file_field :picture %>
   </div>
 <% end %>

Update: (posts/new.html)

 <form action="/posts" method="post">
   <input type="hidden" ... />
   <div class="mb-3">
     <label for="post_picture">Picture</label>
     <input type="file" name="post[picture]" id="post_picture" />
   </div>
 </form>

I was able to match on the name of post[picture] (see answer below) but equally the other suggestions of text of "Picture" and id of post_picture worked.

Upvotes: 1

Views: 318

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49870

attach_file locates the file input element by it's id, name, or associated label text, so picture obviously doesn't match any of those. Without the actual HTML produced by your erb template it's impossible to tell exactly what the attributes for your input are, but taking a guess based on your route names you probably want something like one of the following

attach_file 'post_picture', "#{Rails.root}/spec/files/attachment.jpg" # match id of the file input
attach_file "post[picture]", "#{Rails.root}/spec/files/attachment.jpg" # match name of the file input
attach_file "Picture", "#{Rails.root}/spec/files/attachment.jpg" # match associated label text

The other potential issue you may be dealing with is CSS styling of your file input. If your file input is actually styled to be non-visible and then replaced with some sort of button or image, to make it look nicer, then you will want to use the make_visible option which can be passed to attach_file. That will temporarily adjust the CSS to make the input visible - attach the file - and then reset the CSS to original state. Something like

attach_file 'post_picture', "#{Rails.root}/spec/files/attachment.jpg", make_visible: true

Upvotes: 1

Related Questions