Class: RSpecLog

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec_log.rb

Overview

Class that allows for displaying logs or general messages at that are consistent across rspec tests

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename: DEFAULT_LOG_FILE, newfile: false) ⇒ RSpecLog

Returns a new instance of RSpecLog.



8
9
10
11
12
13
14
15
16
# File 'lib/rspec_log.rb', line 8

def initialize(filename: DEFAULT_LOG_FILE, newfile: false)
  raise 'RSpec must be defined to create RSpec log' if (defined? RSpec).nil?

  @filename = filename
  RSpecLog.write_hash_to_file({}, @filename) if newfile || RSpecLog.load_yaml_log(filename).nil?
  RSpecLog.log_hash_set(YAML.load_file(@filename))

  at_exit { RSpecLog.print_logs_from_file(filename: @filename) }
end

Class Method Details

.add_to_log(name, value) ⇒ Object



39
40
41
42
43
# File 'lib/rspec_log.rb', line 39

def self.add_to_log(name, value)
  log_hash[current_node] = [] if log_hash[current_node].nil?
  log_hash[current_node] << "#{name}, #{value}"
  log_hash_set(log_hash)
end

.current_nodeObject



66
67
68
# File 'lib/rspec_log.rb', line 66

def self.current_node
  ENV.fetch('TARGET_HOST', "#{RSpec.current_example.description}:".blue.bold)
end

.load_yaml_log(filename) ⇒ Object



47
48
49
50
51
52
# File 'lib/rspec_log.rb', line 47

def self.load_yaml_log(filename)
  YAML.load_file(filename)
rescue StandardError => e
  puts e.to_s.yellow
  nil
end

.log_hashObject



58
59
60
# File 'lib/rspec_log.rb', line 58

def self.log_hash
  RSpec.instance_variable_get(:@log_hash)
end

.log_hash_set(item) ⇒ Object



62
63
64
# File 'lib/rspec_log.rb', line 62

def self.log_hash_set(item)
  RSpec.instance_variable_set(:@log_hash, item)
end

Parse the YAML log file and print it out in a nice manner



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rspec_log.rb', line 25

def self.print_logs_from_file(filename: DEFAULT_LOG_FILE)
  file_contents = RSpecLog.load_yaml_log(filename)

  return if file_contents.nil? || file_contents.empty?
  puts 'RSpecLogs:'.blue.underline

  file_contents.each do |key, value|
    puts key
    value.each { |v| puts "  - #{v.to_s.yellow}" }
  end
end

.write_hash_to_file(log_hash, filename = DEFAULT_LOG_FILE) ⇒ Object



54
55
56
# File 'lib/rspec_log.rb', line 54

def self.write_hash_to_file(log_hash, filename = DEFAULT_LOG_FILE)
  File.open(filename, 'w') { |f| f.write(YAML.dump(log_hash, line_width: -1)) }
end

Instance Method Details

#write_file(filename: @filename) ⇒ Object

Writes log_hash to, by default, currently set log file or custom file passed to it



19
20
21
22
# File 'lib/rspec_log.rb', line 19

def write_file(filename: @filename)
  raise 'Filename is not set, you need to initialize RSpecLog before writing' if filename.nil?
  RSpecLog.write_hash_to_file(RSpecLog.log_hash, filename)
end