Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get border style with Capybara

Tags:

ruby

capybara

I need to get a border style of an element. I tried the following code:

sample = page.execute_script("
  var x = window.document.querySelector('#{path}');
  a = window.getComputedStyle(x, null).getPropertyValue('border');
  return a;
")                     
puts sample

It's printing null.

(Note: Border of the element is - Solid)

like image 429
NMKP Avatar asked Dec 27 '22 11:12

NMKP


1 Answers

Based on your previous questions, I am assuming you are using selenium-webdriver.

The native selenium-webdriver element has methods to check computed styles - Element#css_value.

If you have a page HTML of:

<html>
    <body>
        <p style="border-style:solid;">A solid border.</p>
    </body>
</html>

Then you can get the border style using:

puts page.first('p').native.css_value('border-style')
#=> 'solid'

Notice in the code that:

  1. Capybara locates the desired element using page.first('p')
  2. native is used to get the selenium-webdriver element
  3. css_value is used to get the computed style. Note that the css_value method has to be passed the paramater 'border-style' not the shorthand 'border'.

Update:

For your specific example:

  1. It seems that if you use the shorthand "border" property, the "border-style" property will be blank. Instead, you have to use the specific "border-bottom-style", "border-left-style", etc. properties.
  2. Since you know the id of the element, you can get the Capybara element using page.find_by_id('option')

Considering the above, you can check the computed border style using:

puts page.find_by_id('option').native.css_value('border-bottom-style')
#=> "solid"
puts page.find_by_id('option').native.css_value('border-left-style')
#=> "solid"
puts page.find_by_id('option').native.css_value('border-right-style')
#=> "solid"
puts page.find_by_id('option').native.css_value('border-top-style')
#=> "solid"
like image 100
Justin Ko Avatar answered Jan 13 '23 21:01

Justin Ko