Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test file attachment on hidden input using capybara?

I have hidden input inside of label:

<label for="upload">
  <input class="hidden" type="file" name="file[picture]">
</label>

When I click on the label, I attach a file and then confirm.

After that modal window pops up and I need to find appropriate div class.

How can I test this with the help of capybara?

like image 744
Billy Logan Avatar asked Jun 27 '16 08:06

Billy Logan


3 Answers

Update: Capybara 2.12 added a make_visible option to attach_file so if using 2.12+ you can first try

attach_file('file[picture]', 'path/to/file.png', make_visible: true)

before directly using execute_script yourself


File inputs are a special case since they are so often hidden for styling reasons and use a system modal for interaction. Capybara makes it hard to fill in hidden fields on a page because users generally can't interact with them, so for file inputs normal practice is to use execute_script to make them visible and then fill them in.

execute_script("$('input[name=\"file[picture]\"]').removeClass('hidden')") # assumes you have jQuery available - if not change to valid JS for your environment
attach_file('file[picture]', 'path/to/file.png') # takes id, name or label text of field not a random selector
like image 129
Thomas Walpole Avatar answered Nov 12 '22 18:11

Thomas Walpole


Using Capybara '2.7.1':

attach_file('file[picture]', 'path/to/file.png', visible: false)
like image 21
Kuf Avatar answered Nov 12 '22 19:11

Kuf


You can do something along the lines of:

find('label[for=upload]').click
attach_file('input[name="file[picture]"]'), 'path/to/file.png')

within '.modal-popup' do
   expect(page).to have_content '.divclass'
end
like image 2
Ho Man Avatar answered Nov 12 '22 19:11

Ho Man