capybara/selenium with rspec before :all hook

假装没事ソ 提交于 2019-11-30 11:39:32

Cause of problem

The second example doesn't work because because Capybara resets the session after each RSpec example; the page you visit-ed in your before :all block is no longer open at that point. This an explicit behavior of Capybara. It's in the capybara gem, under /lib/capybara/rspec.rb:

config.after do
  if self.class.include?(Capybara::DSL)
    Capybara.reset_sessions!
    Capybara.use_default_driver
  end
end

I Googled around for a couple of hours and found several others struggling with this, to no avail really.

I also found that a patch that would allow Capybara to be configured not to reset the session after each example has been proposed ... but Capybara creator jnicklas declined the pull request.

Solution

The quickest -- though perhaps not the best -- workable solution I've found (so far) is to monkey-patch Capybara thusly:

module Capybara                                                                                                                                                                                  
  class << self                                                                                                                                                                                  
    alias_method :old_reset_sessions!, :reset_sessions!                                                                                                                                          
    def reset_sessions!; end                                                                                                                                                                     
  end                                                                                                                                                                                            
end

This just makes reset_sessions! do nothing when it gets called. Note: Beware of unintended side-effects! (You can always revert the alias_method later on in your code if you need the default resetting behavior to happen again.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!