Introduction
<ul>
<li class="list-item good">Good 1</li>
<li class="list-item good">Good 2</li>
<li class="list-item bad">Bad 1</li>
<li class="list-item bad">Bad 2</li>
</ul>
このようなリストでn番目のli
要素にgood
またはbad
classが適用されているかを検証したい。
have_css
matcherだと指定した要素よりも下の階層しか検証できないようで、
expect(find("ul").all("li")[0]).to have_css ".good"
だとうまくいきませんでした。
Solution 1
class
要素の文字列をinclude
で検証する方法。
expect(find("ul").all("li")[0][:class]).to include "good"
expect(find("ul").all("li")[1][:class]).to include "good"
expect(find("ul").all("li")[2][:class]).to include "bad"
expect(find("ul").all("li")[3][:class]).to include "bad"
each
使うなら下みたいな感じ。
(0...1).each do |i|
expect(find("ul").all("li")[i][:class]).to include "good"
end
(2...3).each do |i|
expect(find("ul").all("li")[i][:class]).to include "bad"
end
Solution 2
nth-child
を使って検証する方法。
expect(find("ul")).to have_css "li:nth-child(1).good"
expect(find("ul")).to have_css "li:nth-child(2).good"
expect(find("ul")).to have_css "li:nth-child(3).bad"
expect(find("ul")).to have_css "li:nth-child(4).bad"
each
使うなら下みたいな感じ。
(1...2).each do |i|
expect(find("ul")).to have_css "li:nth-child(#{i}).good"
end
(3...4).each do |i|
expect(find("ul")).to have_css "li:nth-child(#{i}).bad"
end
Conclusion
Solution 2の方が好み。
配列の場合は0
から、nth-child
の場合は1
から始まるのはややこしや。
Reference
Special Thanks
- jnchitoさん