Search code examples
ruby-on-railscapybaracarrierwavecapybara-webkitcocoon-gem

Multiple files upload with cocoon and capybara


I have issue with testing uploading multiple files with capybara using cocoon. How can I find all fields with id: "image" and attach to each of them file?

Here is my test code:

  click_link "Add photo"
  wait_for_ajax

  click_link "Add photo"
  wait_for_ajax


  page.all(:class, '.attach_fileds').each do |el|
    attach_file( el, "#{Rails.root}/spec/assets/example.jpg")
  end

  click_button "Add"

  expect(Post.count).to eq(1)
  expect(Post.last.images.size).to eq(2)

Error message: Unable to find file field #<Capybara::Element tag="input" path="/html/body/div/div/div/form[@id='new_post']/div[@id='educations']/div[1]/input[@id='image']">


Solution

  • You shouldn't have multiple elements with the same id, since thats illegal html. Based on your sample code (not sure what the :class selector is so guessing) you really want every element with a class of 'attach_field'. #attach_file doesn't take an element as its first parameter, instead it takes the name, id, or label text of the element. Since you already have the elements you can just call #set on each of them

    page.all(:css, '.attach_field').each do |el
      el.set "path of file to upload"
    end
    

    If instead you just want every file input you could do

    page.all(:css, 'input[type="file"]').each do |el|
      el.set "path of file to upload")
    end
    

    Also note that you need something between click_button "Add" and expect(Post.count).to eq(1) to make the test wait for the submission to finish - something like

    expect(page).to have_text('Image Uploaded') # if the page adds text when image is uploaded
    

    or

    expect(page).to have_current_path('/some_new_path') # if the page url changes after the upload is complete