Warm tip: This article is reproduced from stackoverflow.com, please click
cucumber ruby watir

Cucumber : I want to send report on email after my all the scenario get executed, Is there any metho

发布于 2020-04-20 11:05:05

I have created mail function to send my report

class Email
  include PageObject
  require 'mail'

  def mailsender
      Mail.defaults do
        delivery_method :smtp,{ 
          address: "smtp.gmail.com",
          openssl_verify_mode: "none",
          port: 587,
          domain: 'gmail.com',
          user_name: 'xxxxxxxx@gmail.com' ,
          password: '*******' ,
          authentication: 'plain'
        }
      end

      Mail.deliver do
        from     'xxxxxxx.com'
        to       'xxxxx@test.com'
        subject  'Execution report'
        body     'PFA'
        add_file 'Automation_report.html'
      end
  end
end

I want this function will execute after all the scenario get executed.

This is my hook file

# frozen_string_literal: true

require watir

Before do |scenario|
  DataMagic.load_for_scenario(scenario)
  @browser = Watir::Browser.new :chrome
  @browser.driver.manage.window.maximize
end

After do |scenario|
  if scenario.failed?
    screenshot = "./screenshot.png"
    @browser.driver.save_screenshot(screenshot)
    embed(screenshot, "image/png",)
  end
  @browser.close
end

If I use this function in After do then it sends the email every time after each scenario get executed

Questioner
Akshay
Viewed
31
supputuri 2020-02-05 22:17

You can use the at_exit in the hooks.rb file.

at_exit do
   # your email logic goes here
end

Additional notes: After hook will execute after each scenario that's the reason why it will send the email after each scenario executed. On the other hand at_exit hook will execute only after all the scenarios are executed.

You can directly implement the email logic in the at_exit hook. If you want to call mailsender method and not able to access it in the at_exit hook then you can create the email class/module as shown below.

consider that you have Email module under GenericModules

module GenericModules
  module Email
     def mailsender
         # implement your logic here
     end
  end
end

And then add Email module to the world in the env.rb as shown below.

World(GenericModules::Email)

Now you should be able to access the method even in at_exit hook.