I have a Rails project using Cucumber and Capybara for tests. I have a file upload page using Dropzone.js.
My uploads work great using the dialog box or drag and drop. Testing is another matter.
I have the following field in my form:
<input id="photo_image" multiple="multiple" name="image" type="hidden">
However, in the step definitions, I've tried a few methods of finding and attaching the file data, but none of them work.
I've tried fill_in:
fill_in "photo_image", with: photo
I've tried find with css selectors:
find('#photo_image').set photo
I've tried find with xpath:
find(:xpath, "//input[@id='photo_image']").set photo
But none of them see the hidden field.
Unable to find css "#photo_image" (Capybara::ElementNotFound)
Unable to find xpath "//input[@id='photo_image']" (Capybara::ElementNotFound)
Unable to find field "photo_image" (Capybara::ElementNotFound)
Is there any testing method that can handle the upload using Dropzone.js or is it hopeless?
Capybara 2.1 doesn't find hidden elements by default.
You can either set ignore_hidden_elements
to false:
Capybara.ignore_hidden_elements = false
or add :visible
option to your method:
attach_file('photo_image', path_to_file, visible: false)
I prefer the second variant as in most of cases elements to be found in tests are visible and it's better to keep Capybara to throw exception if one of them is hidden.
Note: :visible
option is also supported by most of Capybara methods that internally work with Capybara::Query
(like find
, all
, has_css?
, have_selector
etc.)
Since I just had to help someone figure this out, this is an updated answer for current versions of Capybara and dropzone.js.
By default Dropzone adds a hidden file field to the body of the page at initialization with a class of 'dz-hidden-input'. To add a file to that for testing purposes you can do
attach_file(file_path, class: 'dz-hidden-input', make_visible: true)
Explanation: There is no known id/name/label text so we don't pass a locator, instead we pass the class
option to limit the found file inputs to ones with the specified class. Then we specify the make_visible: true
to have Capybara temporarily change the CSS so the file input becomes visible, adds the file, then restores the original CSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With