Search code examples
rspeccapybaracapybara-webkit

Locate element using Capybara in RSPEC


How can get or locate the element for uploading image when using bootstrap upload file.

Here is my html for upload.

<input id="input-id" name="user[image]" type="file" class="file" data-preview-file-type="text" data-show-preview="false" data-show-upload="false" data-show-caption="true" />

Here is the rendered html in browser:

<span class="file-input file-input-new">
<div class="kv-upload-progress hide"></div>
<div class="input-group ">
   <div tabindex="-1" class="form-control file-caption  kv-fileinput-caption">
   <span class="file-caption-ellipsis">…</span>
   <div class="file-caption-name"></div>
</div>
   <div class="input-group-btn">
       <button type="button" title="Clear selected files" class="btn btn-default fileinput-remove fileinput-remove-button"><i class="glyphicon glyphicon-trash"></i> Remove</button>
       <button type="button" title="Abort ongoing upload" class="hide btn btn-default fileinput-cancel fileinput-cancel-button"><i class="glyphicon glyphicon-ban-circle"></i> Cancel</button>

       <div class="btn btn-primary btn-file"> <i class="glyphicon glyphicon-folder-open"></i> &nbsp;Browse … <input id="input-id" name="user[image]" type="file" class="file" data-preview-file-type="text" data-show-preview="false" data-show-upload="false" data-show-caption="true"></div>
   </div>
</div>
</span>

Here is my Capybara code locating and passing image:

attach_file('what_here', Rails.root + 'public/sample.jpg')

I tried different value for what_here above, but unfortunately i got error:

Failure/Error: attach_file('file-caption', Rails.root + 'public/sample.jpg')

     Capybara::ElementNotFound:
       Unable to find file field "file-caption(tried diff. selector here)"

Please help!


Solution

  • This is failing because the file input is not visible on the page. This is common with file inputs since they're often hidden to allow for other srylable elements to be used. To test them you need to use execute_script to adjust the CSS of the element so it becomes visible on the page and can then call attach_file on it. The CSS you need to add to the element depends on how it's being hidden, opacity, zindex, position, etc. Once you've made it visible then you can do

    attach_file('input-id', ...)