Jason Koelewyn Jason Koelewyn - 2 months ago 24
Ruby Question

Is there a good way to write Cucumber/Watir/Ruby test results to a database?

I am using a Cucumber/Watir/Ruby stack with PageObjects.
I want to store all my test results in a database instead of making prety reports like the pretyface gem.
Has anyone done this?

Thank you

Answer

So there are 2 approaches to try. 1 is to write your own formatter. I have not attempted this yet but that will be my next side project. The second way is to hack all the fields you care about out of the scenario object in the After Hook section. I have done this for a Pre-2.0 version of cucumber. When I look at a Post-2.0 the object does not seem to expose all the data I want, which I suppose is part of the reason the Pretyface gem has still not been updated to work past 1.9.3 or so. the below code is not pretty at all, but it does work. Just call it from the After Hooks method

def read_and_export_scenario_results(scenario)
    set1 = scenario.instance_variable_get(:@current_visitor)

    feature_loc = scenario.feature.location
    feature_name = scenario.feature.title
    feature_desc = scenario.feature.description
    scenario_name = scenario.title
    profile = set1.configuration.options.send(:profiles)[0]
    #get data from Listeners

    results_loc = set1.configuration.options.send(:expanded_args)[set1.configuration.options.send(:expanded_args).size-1]
    run = results_loc.split('/')[2]

    steps = Array.new(set1.runtime.results.steps.count)
    i=0
    set1.runtime.results.steps.each do |step|
      step_hash = Hash.new
      step_hash['StepName'] = step.name
      step_hash['ReportedException'] = step.reported_exception
      step_hash['Status'] = step.status
      step_hash['Message'] = step.multiline_arg
      steps[i] = step_hash
      i += 1
    end

  if scenario.failed?
    pic_dir = 'screenshots'
    pic_name = "ERR_#{run}_#{@current_page.class}_#{Time.now.strftime('%Y-%m-%d_%H-%M-%S')}.png"
    pic_src = "#{pic_dir}\\#{pic_name}"

    unless File.directory?(pic_dir)
      Dir.mkdir(pic_dir)
    end

    @current_page.save_screenshot(pic_src)
    embed(pic_src, 'image/png')
  else
    pic_src = ''
  end
  sql_object = Sql.new
  sql_load_scenario = "AddScenario '#{feature_loc}', '#{feature_name}', '#{feature_desc}', '#{scenario_name}', '#{profile}', '#{run}', '#{pic_src}', '#{results_loc}', '#{FigNewton.application}', '#{FigNewton.base_location}'"
  feature_ID = sql_object.execute_query(sql_load_scenario).to_a[0]
  steps.each do |step|
    sql_load_steps = "AddScenarioStep #{feature_ID}, '#{step['StepName']}', '#{step['Status']}', '#{step['ReportedException']}', '#{step['Message']}'"
    sql_object.execute_query(sql_load_steps)
end
Comments