Search code examples
rubycucumberwatir-webdriver

How to add Date as a variable field in my code to print in a text field (Ruby)


I am writing a quick automation script using Ruby, Cucumber, Watir-webdriver etc. I am creating an ad campaign and want the title of the campaign (a text field I can enter anything into) to contain whatever today's datetime is. Currently my code looks like:

When(/^I enter "([^"]*)" into the campaign name field$/) do |arg1|
  @browser.textarea(:id => 'campaign_name').set('SBTC - Regression - Campaign Create-' Time.now.strftime("%d/%m/%Y %H:%M")) 
end

Obviously that's not correct and I haven't seen anything on the forum on how to do it. End result is that when the automation finishes I have a new ad campaign title "SBTC - Regression - Campaign Create - [TodayDateTime]"


Solution

  • You need to interpolate the Time.now.strftime method so that the code is executed within the string.

    In ruby, this is commonly done by placing the code to-be-executed in curly braces that are preceeded by an octothorpe in a double-quoted string. For example:

    require 'watir-webdriver'
    
    b = Watir::Browser.new :chrome
    b.goto "google.com"
    b.text_field(:name => 'q').set("example of string interpolation: #{Time.now.strftime('%d/%m/%Y %H:%M')}")