Search code examples
webdrivercucumbercapybara

It is possible to attach files by clicking on capybara


I'm using capybara, cucumber and webDriver to perform file tests

I am doing a study and need to attach a file, however the file input does not exist in the dom, and it is only created when the button is clicked, currently my code is like this:

HTML

<a id="input-id" href="#" onClick="callInput">Attach</a>

Script

function callInput(){

    const input = document.createElement("input");
    input.style.display = "none";
    input.type = "file";
    input.click();

}

Solution

  • If it's possible the only way would be using the attach_file block mode

    attach_file('/file/to/be/attached') do
      click_link('Attach')
    end
    

    Since you're setting display to 'none' rather than hiding via setting it offscreen or other methods it's possible the make_visible option could make it work if the above doesn't

    attach_file('/file/to/be/attached', make_visible: true) do
      click_link('Attach')
    end
    

    If neither of those work then it's not possible for Capybara to work with the way you've implemented file upload on your page.

    Note: odds of either working is pretty low because you're never actually attaching the input to the page so events won't get routed anywhere Capybara can detect.