【问题标题】:Rails - Capybara, populate hidden field from trix-editorRails - Capybara,从 trix-editor 填充隐藏字段
【发布时间】:2017-08-30 14:10:38
【问题描述】:

我使用Trix Editor 在我的表单中添加 WISIWIG。我想用 RSpec 和 Capybara 进行测试,但 trix-editor 将字段隐藏了。

<div class="form-group">
  <trix-editor class="formatted_content form-control" placeholder="Description" input="annonce_ad_body_trix_input_annonce_ad"></trix-editor><input type="hidden" name="annonce_ad[body]" id="annonce_ad_body_trix_input_annonce_ad" />
</div>

我需要知道如何用 Capybara 填充这个隐藏字段以使我的测试通过。我已经尝试了这些尝试:

fill_in "annonce_ad[body]", with: "my value"
find(:css, 'trix-editor').set("New text")
find("trix-editor", visible: false).set("my value")
find(:xpath, "//input[@id='annonce_ad_body_trix_input_annonce_ad']", visible: false).set "my value"
find(:xpath, "//*[@id='annonce_ad_body_trix_input_annonce_ad']", visible: false).set("value")
first('input#annonce_ad_body_trix_input_annonce_ad.class', visible: false).set("your value")

这些都不适合我。有人知道在这种情况下如何填充我的身体(用 trix)吗?

【问题讨论】:

    标签: ruby-on-rails rspec capybara trix


    【解决方案1】:

    当使用 Capybara 时,处理非标准控件的规则是模仿用户会做什么。在这种情况下,将单击可见字段(trix-editor 元素),然后键入所需的内容。你永远不应该尝试填充不可见的元素,事实上visible 选项在测试应用程序时应该很少(如果有的话)使用(如果使用 Capybara 进行抓取,这很有意义)。所以在你的情况下应该是

    find('trix-editor').click.set('New text')
    

    它可能在没有点击的情况下工作,但更完全地复制用户并没有什么坏处。由于您已经说过与此非常相似的东西对您不起作用(但没有提供实际错误),我不得不假设您实际上并没有使用支持 JS 的驱动程序。由于 trix 是一个 JS 驱动的编辑器,因此在测试它时需要使用支持 JS 的驱动程序 - https://github.com/teamcapybara/capybara#drivers

    以下基本的 ruby​​ sn-p 显示 Capybara 在 trix-editor.org 上填充演示 trix 编辑器

    require 'capybara/dsl'
    require 'selenium-webdriver'
    
    sess = Capybara::Session.new(:selenium_chrome, nil)
    sess.visit('https://trix-editor.org/')
    editor = sess.find('trix-editor')
    editor.click.set('My test text')
    editor.assert_text('My test text')
    

    【讨论】:

    • 虽然这是执行此操作的正确方法,但值得注意的是 set 方法一次填充其文本一个字符(至少使用 Selenium webdrivers),这会使您的测试花费大量时间较慢,取决于字符串的长度。我在测试具有 130k 个字符的基础字段的最大长度时遇到了这个问题。对我来说唯一可行的选择是回退到自定义 JS 来创建一个 tmp textarea,然后从那里复制和粘贴文本。 .send_keys([:control, 'a']) 然后c 然后v 是你的(hacky)朋友:)
    【解决方案2】:

    我犯了一个错误,这对我有用。

    find(:xpath, "//*[@id='annonce_ad_body_trix_input_annonce_ad']", visible: false).set("some value here")
    

    【讨论】:

    • 这与使用 CSS id 选择器没有什么不同(这对大多数人来说更清晰)find('#announce_ad_body_trix_input_announce_ad', visible: false).set("some value here")。但是,由于它与不可见的元素交互,这意味着您的测试并没有真正测试任何东西,因为它正在做一些用户永远无法做到的事情。
    • 好吧,如果用户摆弄浏览器检查器,他可以测试系统的行为方式,但是使用控制器规范来测试它更容易。我同意stackoverflow.com/a/45965124/299774 - 这是一个很好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多