问题描述
为了减少使用硒的页面访问次数,我想从 before:all
钩子调用visit方法,并用一个命令运行所有示例页面加载。但是,当我指定 before:all
和 before:each
时,浏览器将打开,但从未访问过该URL。下面是一个简化的示例...
In an attempt to reduce the number of page visits with selenium, I wanted to call the visit method from a before :all
hook and run all my examples with a single page load. However, when I specify before :all
vs before :each
, the browser opens, but the url is never visited. Below is a simplified and contrived example...
describe 'foobar', :js => true do
before :all do
Capybara.default_wait_time = 10
obj = Factory(:obj)
visit obj_path(obj)
end
it 'should have foo' do
page.should have_content('foo')
end
it 'should have bar' do
page.should have_content('bar')
end
end
当我将其设置为 before:each
之前,它可以工作,但是页面加载了两次。这是水豚的局限性吗?
When I set it to before :each
, it works, but the page loads twice. Is this a limitation of Capybara?
推荐答案
问题原因
第二个示例不起作用,因为Capybara在每个RSpec示例之后都会重置会话。此时,您在 所访问的页面:all 不再打开。这是水豚的明显行为。它位于 capybara
宝石中,位于 /lib/capybara/rspec.rb
下:
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
我在Google周围搜索几个小时后,发现还有其他几个人为此苦苦挣扎,但无济于事。
I Googled around for a couple of hours and found several others struggling with this, to no avail really.
我还发现了,该漏洞将允许Capybara配置为 not 以重置会话,但建议的是Capybara创建者 jnicklas 。
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.
我找到的最快(虽然可能不是最好)可行的解决方案(到目前为止)就是水豚:
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
这只会使 reset_sessions !
在被调用时什么也不做。注意:当心意外的副作用! (如果以后需要再次执行默认的重置行为,则始终可以在代码中稍后恢复 alias_method
。)
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.)
这篇关于水豚/硒与rspec之前:所有钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!