Search code examples
webdrivercucumbercapybara

attach file in invisible elements with Capybara


I'm starting with capybara, cucumber and webdriver, and I was given the task of testing the upload of an image field.

So I simulated a shipping environment in which I could learn, it worked correctly, however, I need to leave the element "hidden", and I don't know if there is any method for capybara to select it.

So my code went in this direction:

HTML

<input type="file" name="attach-file" style="display: none;">

Capybara/Cucumber

addMedicine_page.attach_file('attach-file', 'assets/asset.jpg')

However it results in an Unable to find visible file field "attach-file" message that is not disabled (Capybara :: ElementNotFound)


Solution

  • If you're going to make the file input element non-visible you have to have some visible element available for the user to interact with which will in turn trigger the file inputs file selection. The best solution in that case is to use the block accepting from of attach_file

    page.attach_file('assets/asset.jpg') do
      # perform whatever action the user would to trigger the file selection
      click_button 'Upload file'
    end
    

    if you can't that to work for you, you really should be able to and it most closely replicates a users behavior therefore making the test most valid, then you can use the make_visible option

    page.attach_file('attach-file', 'assets/asset.jpg', make_visible: true)
    

    which will temporarily make the file input visible, attach a file to it, and then re-hide it. If the standard CSS applied by make_visible by your page doesn't work to make the input visible you can set hash of CSS values to use rather than true

    See https://www.rubydoc.info/github/jnicklas/capybara/Capybara/Node/Actions#attach_file-instance_method