Uploading file by label tag in capybara

2019-08-09 23:26发布

I have problem uploading file by using capybara and cucumber.

The HTML is the following

<div class="dyn-crm-upload-btn-container">
  <label class="btn btn-primary btn-sm" data-bind="visible: newCrmBtnEnabled, enabled: fileEditEnabled">
    <i class="fa fa-plus"></i> 
      <span data-bind="i18n:panels.partnerCrm.new" data-i18n="panels.partnerCrm.new">NEW</span> 
      <input id="dyn-crm-file-input" class="dyn-crm-upload-btn" type="file" name="file" accept=".csv" data-bind="events: { change: setFileToNewName }"></label>
</div>

And if I have manualy choosed a file, the HTML is following in a new div

    <div data-bind="visible: fileUploadVisible" class="dyn-crm-file-upload" style="">
<input type="text" data-bind="value: fileToUpload.name, i18n:[placeholder]panels.partnerCrm.fileUpload.enterName" maxlength="20" class="k-textbox dyn-crm-filename" id="dynCrmFilename" data-value-update="keyup" data-i18n="[placeholder]panels.partnerCrm.fileUpload.enterName" placeholder="File name"> 
<input type="button" data-bind="click: uploadFileCrmFile,i18n:[value]panels.partnerCrm.fileUpload.upload" value="Upload" class="btn btn-primary" data-i18n="[value]panels.partnerCrm.fileUpload.upload"><div class="file-upload-progress-container">
</div>

I have tried this

attach_file(find('file',:visible=>false),File.absolute_path('C:/Users/user/test.csv'))

And this

attach_file('file',File.absolute_path('C:/Users/user/test.csv'))

And some other variations, but I get the following error

 Unable to find file field "file" 

Or when using id

 Unable to find file field "dyn-crm-file-input" 

Also I have tried to execute some scripts before attach_file upload.

I'm using

cucumber 2.1.0
ruby 2.1.6
nokogiri 1.6.6.2
capybara 2.4.4
selenium-webdriver 2.47.1

Thanks in advance :)

EDITED

Here is the link for the css picture: css picture.

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-09 23:51

As I imagined, you will have to use jQuery to change the display:none of your element to display:block, for example.

To achieve tis, you can try with this just before attaching the file:

page.execute_script("$('.dyn-crm-upload-btn-container').css('display','block')")
查看更多
放荡不羁爱自由
3楼-- · 2019-08-10 00:06

Capybara generally can't call attach_file on a non visible file input. To work around this you need to use #execute_script to modify the file inputs css so it becomes visible on the page and then use attach_file on it.

查看更多
登录 后发表回答