【问题标题】:Searching within HTML elements in RSpec view tests在 RSpec 视图测试中搜索 HTML 元素
【发布时间】:2016-04-08 22:29:55
【问题描述】:

作为我的视图规范的一部分,我有时喜欢检查页面上的某个元素是否也呈现了正确的文本。

假设渲染的 HTML 是 -

<div class="user-msg">
  <b>Thank You!</b>
</div>

我可能会在我的视图规范中测试为 -

expect(rendered).to match(/Thank You/)

但是,这可能会错误地失败或通过,具体取决于页面上是否还有其他内容也显示“谢谢”。

如何在有问题的特定&lt;div&gt; 中进行搜索?如果这是一个功能测试,我会使用 Capybara 来选择节点 -

within(".user-mssg") { expect(page.body).to have_content("Thank You") }

如何找到特定的 HTML 元素(例如 .user-msg)并在我的视图规范中搜索?

谢谢!

编辑:“谢谢!”

【问题讨论】:

    标签: ruby-on-rails-4 rspec views


    【解决方案1】:

    rspec-html-matchers 就是这样做的:

    <h1>Simple Form</h1>
    <form action="/users" method="post">
    <p>
      <input type="email" name="user[email]" />
    </p>
    <p>
      <input type="submit" id="special_submit" />
    </p>
    </form>
    

    规格:

    expect(rendered).to have_tag('form', :with => { :action => '/users', :method => 'post' }) do
      with_tag "input", :with => { :name => "user[email]", :type => 'email' }
      with_tag "input#special_submit", :count => 1
      without_tag "h1", :text => 'unneeded tag'
      without_tag "p",  :text => /content/i
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 2017-07-02
      • 2011-02-16
      • 2014-04-25
      • 2018-02-10
      相关资源
      最近更新 更多