【问题标题】:How to test file attachment on hidden input using capybara?如何使用水豚测试隐藏输入的文件附件?
【发布时间】:2016-06-27 08:21:04
【问题描述】:

我在标签内隐藏了输入:

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

当我点击标签时,我会附加一个文件然后确认。

在弹出模态窗口后,我需要找到合适的 div 类。

如何在 capybara 的帮助下进行测试?

【问题讨论】:

    标签: ruby-on-rails rspec capybara


    【解决方案1】:

    更新:Capybara 2.12 为attach_file 添加了make_visible 选项,因此如果使用 2.12+,您可以先尝试

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

    在直接使用execute_script自己之前


    文件输入是一种特殊情况,因为它们经常因样式原因被隐藏并使用系统模式进行交互。 Capybara 很难填写页面上的隐藏字段,因为用户通常无法与它们交互,因此对于文件输入,通常的做法是使用 execute_script 使其可见,然后填写。

    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
    

    【讨论】:

    • make_visible: true +1
    【解决方案2】:

    使用水豚'2.7.1':

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

    【讨论】:

    • 这可以在没有 javascript 的情况下工作(与 make_visible 选项不同)
    【解决方案3】:

    你可以按照以下方式做一些事情:

    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
    

    【讨论】:

    • 我看到这个答案被接受了,但它真的有效吗?它可能适用于 poltergeist 驱动程序,但可能不适用于任何其他驱动程序,因为 attach_file 不会与隐藏字段交互
    • @TomWalpole 你是绝对正确的。我必须将 Capybara.ignore_hidden_elements = false 行添加到我的 rails 助手中才能正常工作。
    • @TomWalpole 设置 visible: false 没有帮助
    • @BillyLogan 它不应该 - Capybara 很难与隐藏字段交互,因为用户不能。对于文件输入,通常的做法是使用 execute_script 使它们可见,然后调用 attach_file。添加ignore_hidden_​​elements = false就像用原子弹杀死苍蝇一样,你以后会后悔的
    • @TomWalpole 谢谢你,汤姆!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    相关资源
    最近更新 更多