2

I have a step that checks for the footer visibility here

And (/^the footer appears$/) do
   within("div.footer") do
      assert_selector "a", :text=> "About"
      ...
   end
end

Basically I load the page and scroll to the bottom then do this check, but I also noticed that this steps works without me having to scroll to the bottom. I did some testing and found out this step only checks for visibility on the entire page. It doesn't check for visibility within the viewport.

I want to have a check that passes only when the element is within the viewport. Is this possible without Rspec and just capybara/ruby/js alone?

chasethesunnn
  • 2,149
  • 5
  • 25
  • 42
  • 1
    It's unlikely to be supported out of the box. It's possible with a JavaScript injection by comparing the rectangle returned by `element.getBoundingClientRect()` with the `window.innerWidth/window.innerHeight`. Another way it to call `elementFromPoint()` at the location and assert that the returned element is your element or a descendant. – Florent B. Mar 30 '18 at 17:54

1 Answers1

3

You can use #evaluate_javascript to check this. Something along the lines of

in_view = evaluate_script("(function(el) {
  var rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 && rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  )
})(arguments[0]);", find('div.footer'))
# assert that in_view is true, or whatever you want.
Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78
  • Thanks for this! Its something I been scratching my head over for a day. Mostly figuring out why assert_selector "div.footer", :visible=>true doesn't work with viewport visibility xD – chasethesunnn Mar 31 '18 at 00:42
  • My actual test case is that I wanted to test the stickiness of an element, like a header navigation element – chasethesunnn Mar 31 '18 at 00:43
  • 1
    @Nils_e assert_selector doesn’t consider viewport because every user has a different window size so it’s generally irrelevant – Thomas Walpole Mar 31 '18 at 07:30