Skip to content

Instantly share code, notes, and snippets.

@alloy-d
Created October 14, 2014 18:17
Show Gist options
  • Save alloy-d/3652d0b8a18ca03ea6e7 to your computer and use it in GitHub Desktop.
Save alloy-d/3652d0b8a18ca03ea6e7 to your computer and use it in GitHub Desktop.
Nonsense with Capybara and threads
require 'thread'
require 'capybara'
Capybara.register_driver :selenium_chrome do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
class SeleniumTest
class SeleniumThread
def initialize(queue, done)
@queue = queue
@done = done
@browser = Capybara::Session.new(:selenium_chrome)
end
def run
begin
loop do
# if (@done.pop(true) rescue false)
# return finish(:done)
# end
if Thread.current[:done]
return finish(:done)
end
url = @queue.pop
@browser.visit(url)
sleep 2
end
rescue Exception => e
finish(:failed, e)
end
end
def finish(*result)
begin
tries = 0
begin
@browser.driver.browser.quit
rescue Exception => e
tries += 1
retry if tries <= 3
raise
end
result
rescue Exception => e
e
end
end
end
def initialize(nthreads=1)
@queue = Queue.new
@done = Queue.new
@threads = nthreads.times.map do
Thread.new do
t = SeleniumThread.new(@queue, @done)
t.run
end
end
end
def run(urls=nil)
@urls = urls || %w{
http://google.com
http://ddg.gg
http://yahoo.com
http://jibe.com
http://twitter.com
http://facebook.com
http://github.com
}
@urls.each {|u| @queue << u }
loop do
if @queue.empty?
puts "Done!"
@threads.each do |thread|
thread[:done] = true
end
break
end
end
@threads.map(&:value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment