I have a very simple test in Rspec/Capybara that is exhibiting some strange behavior. When I run the test using rspec <filename>
, Capybara fails to click the button and so the test fails. If I pry
the test, and copy/paste the exact same line of code, the button clicks and the test passes. I'm trying to figure out how to debug the discrepancy.
The test:
context "when menu is open" do
before do
visit root_path
page.find("svg", class: "fa-bars").click
end
it "shows bars again once closed" do
page.find("svg", class: "fa-times").click(wait: 5)
expect(page).to have_css(".fa-bars")
end
end
Putting a binding.pry
before the find/click, and then running that line, works fine. I'm kind of stumped as to why the behavior is so different.
Our system tests run on Selenium:
config.before(:each, type: :system) do
if !!ENV['SYSTEM_TESTS_BROWSER_MODE']
driven_by :selenium, using: :firefox
else
driven_by :selenium_headless
end
end
CodePudding user response:
When you say "fails to click", I'm assuming you don't mean you're getting an error from the page.find("svg", class: "fa-times").click(wait: 5)
but rather that the line is proceeding just fine and your expect(page).to have_css(".fa-bars")
is what's actually failing.
Given that, your description tells me that Capybara is actually clicking just fine, but it's happening before the menu is ready to interpret the click as meaning to close. When you add a binding.pry you're giving the menu time to finish opening. The thing you need to understand about passing the wait
parameter is that it sets the maximum amount of time Capybara will wait for the element to exist. If the element exists before that time Capybara will move on, so setting wait: 10
when wait: 5
didn't error on that line will make no difference (condition was met already - allowing it to wait longer is meaningless). You can confirm this by just putting a sleep(2)
before the find/click line to delay the find and click long enough for the menu to open before the click happens to close it. The proper fix for your tests is to either disable animation in your testing environment (so the menu opens instantly) or add an extra expectation for some state of the menu that indicates it is actually fully open and ready to receive a click that closes it.