Method: Capybara::Node::Actions#attach_file

Defined in:
lib/capybara/node/actions.rb

#attach_file([locator], paths, **options) ⇒ Capybara::Node::Element

Find a descendant file field on the page and attach a file given its path. The file field can be found via its name, id or label text. In the case of the file field being hidden for styling reasons the `make_visible` option can be used to temporarily change the CSS of the file field, attach the file, and then revert the CSS back to original. If no locator is passed this will match self or a descendant.

# will attach file to a descendant file input element that has a name, id, or label_text matching 'My File'
page.attach_file('My File', '/path/to/file.png')

# will attach file to el if it's a file input element
el.attach_file('/path/to/file.png')

If the driver is capable of executing JavaScript, this method will wait for a set amount of time and continuously retry finding the element until either the element is found or the time expires. The length of time find will wait is controlled through Capybara.default_max_wait_time

Parameters:

  • locator (String)

    Which field to attach the file to

  • paths (String, Array<String>)

    The path(s) of the file(s) that will be attached

Options Hash (**options):

  • wait (false, Numeric) — default: Capybara.default_max_wait_time

    Maximum time to wait for matching element to appear.

  • match (Symbol) — default: Capybara.match

    The matching strategy to use (:one, :first, :prefer_exact, :smart).

  • exact (Boolean) — default: Capybara.exact

    Match the exact label name/contents or accept a partial match.

  • multiple (Boolean)

    Match field which allows multiple file selection

  • id (String, Regexp)

    Match fields that match the id attribute

  • name (String)

    Match fields that match the name attribute

  • class (String, Array<String>, Regexp)

    Match fields that match the class(es) provided

  • make_visible (true, Hash)

    A Hash of CSS styles to change before attempting to attach the file, if `true` { opacity: 1, display: 'block', visibility: 'visible' } is used (may not be supported by all drivers)

Returns:



257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/capybara/node/actions.rb', line 257

def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments
  Array(paths).each do |path|
    raise Capybara::FileNotFound, "cannot attach file, #{path} does not exist" unless File.exist?(path.to_s)
  end
  options[:allow_self] = true if locator.nil?
  # Allow user to update the CSS style of the file input since they are so often hidden on a page
  if make_visible
    ff = find(:file_field, locator, options.merge(visible: :all))
    while_visible(ff, make_visible) { |el| el.set(paths) }
  else
    find(:file_field, locator, options).set(paths)
  end
end