Capybara doesn't recognize dynamically added DOM elements?

可紊 提交于 2019-12-02 19:15:24

I use the Webdriver based driver for Capybara in RSpec, which I configure and use like this and it will definitely handle JS and doesn't need a reload of the dom. The key is using a wait_until and a condition that will be true when your AJAX response has finished.

before(:each) do
  select_driver(example)  
  logout
  login('databanks') 
end

 def select_driver(example)
   if example.metadata[:js]
    Capybara.current_driver = :selenium
  else
    Capybara.use_default_driver
  end
end

it "should let me delete a scenario", :js=>true do
    select("Mysite Search", :from=>'scenario_id')  
    wait_until{ page.has_content?('mysite_searchterms')}    
    click_on "delete"     
    wait_until{ !page.has_content?('mysite_searchterms')}   
    visit '/databanks'
    page.should_not have_content('Mysite Search')
  end

I also figured out a hack to slow down webdriver last night, like this, if you want to watch things in slo-mo:

   #set a command delay
   require 'selenium-webdriver'

   module ::Selenium::WebDriver::Remote
     class Bridge
       def execute(*args)
         res = raw_execute(*args)['value']
         sleep 0.5
         res
       end
     end
   end  

As someone else mentioned, if you are getting a timeout waiting for the element, you could look at upping this:

Capybara.default_wait_time = 10

From the Capybara docs:

When working with asynchronous JavaScript, you might come across situations where you are attempting to interact with an element which is not yet present on the page. Capybara automatically deals with this by waiting for elements to appear on the page.

You might have some luck increasing the wait time:

Capybara.default_wait_time = 10

If that doesn't help then I would encorage you to contact somebody from the project on GitHub, write to the mailing list or submit an issue report.

Even wait_until deleted from Capybara 2.0. Still that's useful and grab code from below:

 def wait_until(delay = 1)   
 seconds_waited = 0   
 while ! yield && seconds_waited < Capybara.default_wait_time     
    sleep delay     
    seconds_waited += 1   
  end   
  raise "Waited for #{Capybara.default_wait_time} seconds but condition did not become true" unless yield 
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!