Ayrad
Ayrad

Reputation: 4056

testing show/hide with minitest capybara rails

I'm trying to test the visibility of a div after clicking a button.

   assert page.find("#visu")[:class].include?("hidden") # this passes
   assert page.has_xpath?("//*[@id='visu'][contains(@style, 'display: none')]")
   click_button("Show/hide")
   assert page.has_xpath?("//*[@id='visu'][contains(@style, 'display: block')]")

Unfortunately this doesn't work. Any tips?

I am using 'minitest-rails-capybara'

Upvotes: 1

Views: 1520

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49950

By default Capybara only finds visible elements, so if you're using one of the drivers that fully processes CSS (pretty much anything except rack_test) then just doing

assert_selector(:css, '#visu')  

would be enough to check for a visible element. If you want to check that an element is specifically non-visible you would need to do

assert_selector(:css, '#visu', visible: :hidden)

Therefore to test that an element was hidden and then became visible you could do

assert_selector(:css, '#visu', visible: :hidden)
click_button("Show/hide")
assert_selector(:css, '#visu')

Note that it may not actually make sense to check an element exists but is not-visible it may make more sense to just check that the element isn't there (could be hidden, may not exist) since that way if the button behavior changes to loading the element ( or rendering a template ) the test wouldn't break (and the change in behavior wouldn't have changed the users experience). To do that you could just do

refute_selector(:css, '#visu') # or assert_no_selector depending on preference
click_button('Show/hide')
assert_selector(:css, '#visu')

If on the other hand you are using the rack_test driver, it only processes a subsection of CSS/attributes to determine visibility. In that case an element is considered non-visible if the elements inline style attribute contains display: none/display:none or if the element has a hidden attribute (not a class name of 'hidden'). So if the element was being hidden by a class name 'hide_me' that applied display:none in an external css file rack_test would not consider that element hidden. Instead you could do something like

assert_selector(:css, '#visu.hide_me')

and the full test would be something like

assert_selector(:css, '#visu.hide_me')
click_button("Show/hide")
assert_selector(:css, '#visu:not(.hide_me)')

Note: the :css selector type parameter can be omitted if you have not changed Capybara.default_selector. Additionally error messages are going to be much more descriptive using the assert_selector assertion rather than doing assert page.has_xxx?

Upvotes: 4

Related Questions