Billy Logan
Billy Logan

Reputation: 2520

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?

Upvotes: 13

Views: 5929

Answers (3)

Kuf
Kuf

Reputation: 17828

Using Capybara '2.7.1':

attach_file('file[picture]', 'path/to/file.png', visible: false)

Upvotes: 12

Thomas Walpole
Thomas Walpole

Reputation: 49890

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

Upvotes: 30

Ho Man
Ho Man

Reputation: 2345

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

Upvotes: 2

Related Questions