Skip to content

Instantly share code, notes, and snippets.

@DylanLacey
Last active March 2, 2017 03:44
Show Gist options
  • Select an option

  • Save DylanLacey/f62b67cbff6b9cc063a334bf90a88d76 to your computer and use it in GitHub Desktop.

Select an option

Save DylanLacey/f62b67cbff6b9cc063a334bf90a88d76 to your computer and use it in GitHub Desktop.
Prevent Capybara from opening sessions just to close them again
# Allow browser creation to be turned off when calling the 'browser' method.
# This lets us check if a browser has been created, without creating on in the
# process. Which is less gross then `instance_variable_get` IMO.
#
# Default of `true` means standard behavior still exists
module SauceBrowserCheck
def browser allow_creation: true
if (@browser || allow_creation)
super()
else
nil
end
end
end
# Logs when a session is created and destroyed
module LoggingBridge
def write_to_log messages, call_stack_range
parallel_id = ENV["TEST_ENV_NUMBER"] || 1
timestamp = Time.now
logger = $SAUCE_LOGGER || Logger.new(STDOUT)
log_lead = "[#{timestamp}] - Thread #{parallel_id} -"
log_separator = "============================================="
logger.debug log_separator
messages.each { |msg| logger.puts "#{log_lead} #{msg}" }
# We want the call stack as it was when the method was called, not when the
# formatter ran, so take four entries off
call_stack_range.each do |i|
j = i + 3
logger.debug "#{log_lead} called from #{caller[j]}"
end
logger.debug log_separator
end
def initialize opts={}
caps = opts[:desired_capabilities]
super opts
self.write_to_log(
["Created #{self.session_id}",
"Named \"#{caps[:name]}\""],
(3..6))
return self
end
def quit
self.write_to_log(
["Quitting #{session_id}"],
(1..3))
super
end
end
class Capybara::Selenium::Driver
prepend SauceBrowserCheck
end
class Selenium::WebDriver::Remote::Bridge
prepend LoggingBridge
end
@waynerobinson
Copy link

Should probably be logger = $SAUCE_LOGGER || Logger.new(STDOUT)

@waynerobinson
Copy link

And anywhere you use it should probably use the real debug/info/warn/error logger messages.

Loggers can get complex when you're shipping between different apps running all over the place and so it's better to conform to a Logger API than to write to IO directly.

@waynerobinson
Copy link

Generally it's fine though. It might be nice to see it in a block, but I guess I need to see an actual example as well to decide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment