-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
save_and_open_page.rb
51 lines (43 loc) · 1.74 KB
/
save_and_open_page.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module Capybara
class << self
def save_page(html, file_name=nil)
file_name ||= "capybara-#{Time.new.strftime("%Y%m%d%H%M%S")}#{rand(10**10)}.html"
name = File.join(*[Capybara.save_and_open_page_path, file_name].compact)
unless Capybara.save_and_open_page_path.nil? || File.directory?(Capybara.save_and_open_page_path )
FileUtils.mkdir_p(Capybara.save_and_open_page_path)
end
FileUtils.touch(name) unless File.exist?(name)
tempfile = File.new(name,'w')
tempfile.write(rewrite_css_and_image_references(html))
tempfile.close
tempfile.path
end
def save_and_open_page(html, file_name=nil)
open_in_browser save_page(html, file_name)
end
protected
def open_in_browser(path) # :nodoc
require "launchy" # could raise LoadError
raise LoadError unless Launchy::Version::MAJOR >= 2
Launchy.open(path)
rescue LoadError
warn "Sorry, you need to install launchy >=2.0.0 (`gem install launchy`) and " <<
"make sure it's available to open pages with `save_and_open_page`."
end
def rewrite_css_and_image_references(response_html) # :nodoc:
root = Capybara.asset_root
asset_servers = Capybara.asset_servers
return response_html unless (root or asset_servers)
(asset_servers || {}).each_pair do |asset_server, server_assets|
response_html.gsub!(/("|')\/(#{server_assets.join('|')})/, '\1' + asset_server.to_s + '/\2')
end
directories = Dir.new(root).entries.select { |name|
(root+name).directory? and not name.to_s =~ /^\./
}
if not directories.empty?
response_html.gsub!(/("|')\/(#{directories.join('|')})/, '\1' + root.to_s + '/\2')
end
return response_html
end
end
end