7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】RSpecでリストのn番目の要素のclass属性を検証したい

Last updated at Posted at 2019-02-24

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またはbadclassが適用されているかを検証したい。
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さん
7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?