Search code examples
rubyexcelcellwatir

Using excel to log results in ruby watir. how to keep values in different cells using puts


I am new to ruby watir and need your help.

I am using the following commands to log my script results into an excel sheet.

File.open('c:\log.txt', 'w') do |file|
  file.puts("TEST PASSED" + "#{Time.now}")
end

Here the test passed and the time is getting displayed in a single cell itself.

I want to display both of it in different cells.

Please suggest a solution. Thanks in advance!


Solution

  • you are logging to a file called log.txt which appears to be a plain text file. if you want your file to be an excel file you will need a format, the easiest one to write to is either .csv or .tsv which stands for comma separated variable and tab separated variables. You could then write in a few different ways. You could write as you were with:

    File.open('c:\log.tsv', 'w') do |file|
      file.puts("TEST PASSED\t" + "#{Time.now}")
    end
    

    for a tsv (note that it doesn't need to be called .tsv)

    File.open('c:\log.csv', 'w') do |file|
      file.puts("TEST PASSED," + "#{Time.now}")
    end
    

    for a csv

    or you could use the standard csv library. like so:

    CSV.open("c:\log.csv", "wb") do |csv|
      csv << ["TEST PASSED", "#{Time.now}"]
    end
    

    which you can manipulate for tsv's:

    CSV.open("c:\log.csv", "wb", { :col_sep => "\t" }) do |csv|
      csv << ["TEST PASSED", "#{Time.now}"]
    end