2016-04-08 35 views
2

作爲我的視圖規範的一部分,我有時希望檢查頁面上某個元素是否也顯示正確的文本。在RSpec視圖中的HTML元素內搜索測試

比方說呈現的HTML是 -

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

我可能在我看來規格測試爲 -

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

然而,這可能錯誤地失敗或通取決於是否有在頁面上別的東西也說「謝謝你」。

如何在特定的<div>中搜索相關問題?如果這是一個功能的測試,我會使用水豚選擇節點 -

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

如何找到特定HTML元素(例如.user-msg)在我查看規格內搜索它?

謝謝!

編輯:「謝謝你!」

回答

5

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