juhlila juhlila - 4 months ago 10
Ruby Question

how to share a rake variable in the code it invokes?

What I need is basically send a target argument and use it in my RSpec tests, e.g.:

$ rake unistall_and_run[test_spec.rb]


Rakefile:

desc 'uninstall app to run tests'
task :uninstall_and_run, [:arg] do |t, arg|
#note this, i will explain later
start_driver(fullReset: true)

oi = arg.to_s.split('"')[1]
file_dir = (project_home + '/spec/' + oi)
exec "rspec #{file_dir}"
end


start_driver
is called on that line, but when I run the tests (
exec "rspec ..."
), it is called again and the args I passed is overwritten by the default (because its on RSpec config).

What I'd like to do is, on my RSpec file check if it was already called and don't run again.

Here is the start_driver method:

def start_driver(options= {})
if options.empty?
capabilities = caps
else
capabilities = caps(options)
end
$appium = Appium::Driver.new(caps: capabilities)
$browser = $appium.start_driver
Appium.promote_appium_methods RSpec::Core::ExampleGroup
end

Answer

So, i found a way to do it. Its not beautiful though. I save a file with the args I want when run rake:

    desc 'uninstall app to run tests'
      task :uninstall_and_run, [:arg] do |t, arg|
        send_custom_caps(fullReset: true)
        oi = arg.to_s.split('"')[1]
        file_dir = (project_home + '/spec/' + oi)
        exec "rspec #{file_dir}"
      end

and the send_custom_caps method is:

  def send_custom_caps(*opts)
    ENV['CAPS'] = 'true' 
    file = File.new(custom_caps_file, "w+")
    File.open(file, 'w') do |f|
      f.write(opts)
    end
  end

now the ruby code itself (in this case, my spec config) will check if there is custom args before start_driver. Here is my custom start_driver method (which I renamed):

  def start_appium_driver (options= {})
    if options.empty?
      get_caps
      if $custom_args
        capabilities = caps($custom_args)
      else
        capabilities = caps
      end
    else
      capabilities = caps(options)
    end
    $appium = Appium::Driver.new(caps: capabilities)
    $browser = $appium.start_driver
    Appium.promote_appium_methods RSpec::Core::ExampleGroup
  end

and get_caps

  def get_caps
    if File.exist?(custom_caps_file) #$custom_args
      file = File.read(custom_caps_file)
      $custom_args = eval(file)
      File.delete (custom_caps_file)
    end
    $custom_args unless $custom_args.defined?
  end

probably this is not the best solution, but it is working ok for me :)

Comments