4

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?

1
  • Which driver are you using? Commented Apr 15, 2014 at 14:35

3 Answers 3

9

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".
Sign up to request clarification or add additional context in comments.

Comments

0

you can use execute_script, hope this help.

 expect(page.execute_script("return window.getComputedStyle($('your-class-or-id')[0]).color").to eq('rgb(255, 255, 255)')

Comments

0

You can use element.style to get computed styles:

element.style('color', 'font-size') # Returns a hash

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.