Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a div has a certain css style in rspec/capybara?

Not a repeat of: How do you test if a div has a certain css style in rspec/capybara?

because those answers don't work for my case.

I have a webform with a preview; as you change certain parts of the web form, the previews update, and I want to check for this in my tests - so I really do need to check the styling that is applied to a div. Specifically, I'm updating the background-color of certain divs, and I want to check that this has happened.

Any ideas?

like image 449
Narfanator Avatar asked Dec 25 '22 10:12

Narfanator


1 Answers

To my knowledge, Capybara does not have an API for getting the computed style of an element. However, since you are using Selenium-Webdriver, you can drop down to the Selenium element and use the style method.

For example, consider the following page which has a div element whose style is updated via javascript:

<html>
  <body>
    <div id="red_div">
      background applied by javascript
    </div>
    <script>
      document.getElementById("red_div").style.background = "red";
    </script>
  </body>
</html>

You can get the computed style of the div by using the style (or css_value) method of the underlying Selenium element:

red_div = page.find(:css, '#red_div')
puts red_div.native.style('background-color')
#=> "rgba(255, 0, 0, 1)"

Note:

  • native is the method to get the underlying Selenium element of a Capybara node.
  • The value you get from style may vary across browsers. For example, for background-color, I believe IE would actually give you "red".
like image 177
Justin Ko Avatar answered Jan 11 '23 17:01

Justin Ko