Home > OS >  Capybara rspec - attach file to hidden file_field
Capybara rspec - attach file to hidden file_field

Time:11-04

I've got below form:

<%= f.hidden_field :document_type, value: item %>
<%= f.label :file, 'Upload', class: "btn btn-outline-primary btn-sm custom-btn-sm", id: "upload_kyc_#{idx}", name: "upload_button" %>
<%= f.file_field :file, class: "inputfile", accept: "jpeg, .jpg, .png, .pdf", onchange: 'this.form.requestSubmit()' %>

custom_styles.scss

.inputfile {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1;
}

Which produces me in the browser:

enter image description here

Now I want to test this using Capybara. So what I did was:

def pdf_path
  "#{Rails.root}/spec/fixtures/files/sample.pdf"
end

it 'show message' do
  login_as user
  visit profile_path

  attach_file('upload_kyc_0', pdf_path, visible: true)
end

But I gets an error:

 Capybara::ElementNotFound:
   Unable to find file field "inputfile" that is not disabled within #<Capybara::Node::Element tag="div" path="/HTML/BODY[1]/DIV[1]/DIV[1]/DIV[2]">

How to submit that file then?

CodePudding user response:

With:

attach_file('upload_kyc_0', pdf_path, visible: true)` 

you're trying to attach to the label, not to the file input. It should be:

attach_file('file', pdf_path, visible: true)

CodePudding user response:

Pass a block to attach_file with the actions the user would take to upload

attach_file(pdf_path) do
  find(:label, 'Upload').click
end
  • Related