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

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

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)
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 :)

Related

RSpec why is before(:each) never executed?

I have this simple code
require 'json'
module Html
class JsonHelper
attr_accessor :path
def initialize(path)
#path = path
end
def add(data)
old = JSON.parse(File.read(path))
merged = old.merge(data)
File.write(path, merged.to_json)
end
end
end
and this spec (reduced as much as I could while still working)
require 'html/helpers/json_helper'
describe Html::JsonHelper do
let(:path) { "/test/data.json" }
subject { described_class.new(path) }
describe "#add(data)" do
before(:each) do
allow(File).to receive(:write).with(path, anything) do |path, data|
#saved_string = data
#saved_json = JSON.parse(data)
end
subject.add(new_data)
end
let(:new_data) { { oldestIndex: 100 } }
let(:old_data) { {"test" => 'testing', "old" => 50} }
def stub_old_json
allow(File).to receive(:read).with(path).and_return(#data_before.to_json)
end
context "when given data is not present" do
before(:each) do
puts "HERE"
binding.pry
#data_before = old_data
stub_old_json
end
it "adds data" do
expect(#saved_json).to include("oldestIndex" => 100)
end
it "doesn't change old data" do
expect(#saved_json).to include(old_data)
end
end
end
end
HERE never gets printed and binding.pry doesn't stop execution and tests fail with message No such file or directory # rb_sysopen - /test/data.json
This all means that before(:each) never gets executed.
Why?
How to fix it?
It does not print desired message because it fails at the first before block. Rspec doc about execution order
It fails because you provided an absolute path, so it is checking /test/data.json
Either use relative path to the test ie. ../data.json (just guessing),
or full path.
In case of rails:
Rails.root.join('path_to_folder_with_data_json', 'data.json')

Ruby tests don't run

I'm trying Ruby and Unit Testing but my simple attempts at running test cases are returning nothing. The curious thing is that the tests were running before and returning the number of tests that were ran and the number of assertions and so on. But for some reason they stopped running. I have two separated files:
#TipoMovimento.rb
class TipoMovimento
attr_accessor :designacao
attr_accessor :cor
attr_accessor :regras
def initialize(aDesignacao, aCor, asRegras)
#designacao = aDesignacao
#cor = aCor
#regras = asRegras
end
def ==(other)
other.class == self.class && other.state == self.state
end
def state
self.instance_variables.map { |variable| self.instance_variable_get variable }
end
end
and
#TesteTipoMovimento.rb
require './TipoMovimento.rb'
require 'test/unit'
class TesteTipoMovimento < Test::Unit::TestCase
def setup
#tm = TipoMovimento.new('Des1', 'Cor1', ['r1', 'r2'])
end
def tc_equal
tm2 = TipoMovimento.new('Des1', 'Cor1', ['r1', 'r2'])
assert_true(tm2 == #tm)
tm2 = TipoMovimento.new('Des2', 'Cor1', ['r1', 'r2'])
assert_false(tm2 == #tm)
end
end
Both files are in the same folder. Unfortunately, when I run the test file, nothing happens. After I press enter the prompt simply ignores my command. Something like:
C:\My Ruby Files\>ruby TesteTipoMovimento.rb
C:\My Ruby Files\>
This is obviously something simple that I'm missing, so if anyone could help me I would appreciate it. Thanks!
You have no tests in that test class. To make method a test, prefix its name with test_.
class TesteTipoMovimento < Test::Unit::TestCase
def setup
#tm = TipoMovimento.new('Des1', 'Cor1', ['r1', 'r2'])
end
def test_tc_equal
tm2 = TipoMovimento.new('Des1', 'Cor1', ['r1', 'r2'])
assert_true(tm2 == #tm)
tm2 = TipoMovimento.new('Des2', 'Cor1', ['r1', 'r2'])
assert_false(tm2 == #tm)
end
end

OS specific tests with ruby

I've the following Rakefile
require 'bundler/gem_tasks'
require 'rake/testtask'
Rake::TestTask.new do |task|
task.libs << %w(test lib)
task.pattern = 'test/**/*_test.rb'
end
task default: :test
And test are defined with minitest:
require 'test_helper'
require 'certmanager'
class CertificateTest < Minitest::Test
context 'settings' do
should 'retrieve settings' do
assert_equal 'test123', Certmanager::Settings.key_passphrase
end
end
end
Now there is also some OS specific code like FileUtils.ln_s on Linux and FileUtils.cp on Windows. This code requires different tests. In this case e.g. assert_equal filepath, File.readlink(linkpath) (Linux) vs. assert File.exist?(filepath) (windows)
What is the best practice to differentiate between OS Types?
Do I have t write the tests in a way that Linux can test windows specific code and vice versa?
Is it possible to differentiate "inline" in an test?
Is it necessary to have two different testsets and decide in the Rakefile which set needs to be executed? Is it even possible int the Rakefile?
In order to be able to run every test regardless of the current OS, i wrote a module TestHelper. This module contains severall methods to
pretend a windows or posix environment for the test
setup stubs for methods that are not implemented (or work in a different way) on the actual OS - currently I've only found those methods on windows
check if the actual OS is windows or not (if it is necessary to know)
In the test it is possible to simply use TestHelper.setup_windows_env or TestHelper.setup_posix_env whenever it has to be OS specific.
require 'rbconfig'
require 'fileutils'
module TestHelper
extend self
def setup_windows_env
is_windows?
RbConfig::CONFIG.stubs(:[]).with('host_os').returns('windows')
ENV.stubs(:[]).with('OS').returns('Windows_NT')
end
def setup_stubs_for_windows_in_posix_env
class << FileUtils
def ln_s(src, dest, options = {})
File.open(dest, 'w') { |file| file.write src }
return 0
end
end
class << File
def readlink(file_name)
return File.read(file_name)
end
end
end
def setup_posix_env
setup_stubs_for_windows_in_posix_env if is_windows?
RbConfig::CONFIG.stubs(:[]).with('host_os').returns('darwin')
ENV.stubs(:[]).with('OS').returns('OSX')
end
def is_windows?
#is_windows ||= ApplicationToTest::Util::OS.is_windows?
end
end
For completeness ApplicationToTest::Util::OS.is_windows?:
require 'rbconfig'
module ApplicationToTest
module Util
module OS
def self.is_windows?
begin
env_os = ENV['OS']
rescue NameError
return false
end
if RbConfig::CONFIG['host_os'] =~ /^mingw2$|^mingw$|^mswin$|^windows$/
true
elsif env_os == 'Windows_NT'
true
else
false
end
end
end
end
end

How to extract tasks and variables from a Rakefile?

I need to:
Open a Rakefile
Find if a certain task is defined
Find if a certain variable is defined
This works to find tasks defined inside a Rakefile, but it pollutes the global namespace (i.e. if you run it twice, all tasks defined in first one will show up in the second one):
sub_rake = Rake::DefaultLoader.new
sub_rake.load("Rakefile")
puts Rake.application.tasks
In Rake, here is where it loads the Makefile:
https://github.com/ruby/rake/blob/master/lib/rake/rake_module.rb#L28
How do I get access to the variables that are loaded there?
Here is an example Rakefile I am parsing:
load '../common.rake'
#source_dir = 'source'
desc "Run all build and deployment tasks, for continuous delivery"
task :deliver => ['git:pull', 'jekyll:build', 'rsync:push']
Here's some things I tried that didn't work. Using eval on the Rakefile:
safe_object = Object.new
safe_object.instance_eval("Dir.chdir('" + f + "')\n" + File.read(folder_rakefile))
if safe_object.instance_variable_defined?("#staging_dir")
puts " Staging directory is " + f.yellow + safe_object.instance_variable_get("#staging_dir").yellow
else
puts " Staging directory is not specified".red
end
This failed when parsing desc parts of the Rakefile. I also tried things like
puts Rake.instance_variables
puts Rake.class_variables
But these are not getting the #source_dir that I am looking for.
rakefile_body = <<-RUBY
load '../common.rake'
#source_dir = 'some/source/dir'
desc "Run all build and deployment tasks, for continuous delivery"
task :deliver => ['git:pull', 'jekyll:build', 'rsync:push']
RUBY
def source_dir(ast)
return nil unless ast.kind_of? AST::Node
if ast.type == :ivasgn && ast.children[0] == :#source_dir
rhs = ast.children[1]
if rhs.type != :str
raise "#source_dir is not a string literal! #{rhs.inspect}"
else
return rhs.children[0]
end
end
ast.children.each do |child|
value = source_dir(child)
return value if value
end
nil
end
require 'parser/ruby22'
body = Parser::Ruby22.parse(rakefile_body)
source_dir body # => "some/source/dir"
Rake runs load() on the Rakefile inside load_rakefile in the Rake module. And you can easily get the tasks with the public API.
Rake.load_rakefile("Rakefile")
puts Rake.application.tasks
Apparently that load() invocation causes the loaded variables to be captured into the main Object. This is the top-level Object of Ruby. (I expected it to be captured into Rake since the load call is made in the context of the Rake module.)
Therefore, it is possible to access instance variables from the main object using this ugly code:
main = eval 'self', TOPLEVEL_BINDING
puts main.instance_variable_get('#staging_dir')
Here is a way to encapsulate the parsing of the Rakefile so that opening two files will not have all the things from the first one show up when you are analyzing the second one:
class RakeBrowser
attr_reader :tasks
attr_reader :variables
include Rake::DSL
def task(*args, &block)
if args.first.respond_to?(:id2name)
#tasks << args.first.id2name
elsif args.first.keys.first.respond_to?(:id2name)
#tasks << args.first.keys.first.id2name
end
end
def initialize(file)
#tasks = []
Dir.chdir(File.dirname(file)) do
eval(File.read(File.basename(file)))
end
#variables = Hash.new
instance_variables.each do |name|
#variables[name] = instance_variable_get(name)
end
end
end
browser = RakeBrowser.new(f + "Rakefile")
puts browser.tasks
puts browser.variables[:#staging_dir]

Thor::Group do not continue if a condition is not met

I'm converting a generator over from RubiGen and would like to make it so the group of tasks in Thor::Group does not complete if a condition isn't met.
The RubiGen generator looked something like this:
def initialize(runtime_args, runtime_options = {})
super
usage if args.size != 2
#name = args.shift
#site_name=args.shift
check_if_site_exists
extract_options
end
def check_if_site_exists
unless File.directory?(File.join(destination_root,'lib','sites',site_name.underscore))
$stderr.puts "******No such site #{site_name} exists.******"
usage
end
end
So it'd show a usage banner and exit out if the site hadn't been generated yet.
What is the best way to recreate this using thor?
This is my task.
class Page < Thor::Group
include Thor::Actions
source_root File.expand_path('../templates', __FILE__)
argument :name
argument :site_name
argument :subtype, :optional => true
def create_page
check_if_site_exists
page_path = File.join('lib', 'sites', "#{site_name}")
template('page.tt', "#{page_path}/pages/#{name.underscore}_page.rb")
end
def create_spec
base_spec_path = File.join('spec', 'isolation', "#{site_name}")
if subtype.nil?
spec_path = base_spec_path
else
spec_path = File.join("#{base_spec_path}", 'isolation')
end
template('functional_page_spec.tt', "#{spec_path}/#{name.underscore}_page_spec.rb")
end
protected
def check_if_site_exists # :nodoc:
$stderr.puts "#{site_name} does not exist." unless File.directory?(File.join(destination_root,'lib','sites', site_name.underscore))
end
end
after looking through the generators for the spree gem i added a method first that checks for the site and then exits with code 1 if the site is not found after spitting out an error message to the console. The code looks something like this:
def check_if_site_exists
unless File.directory?(path/to/site)
say "site does not exist."
exit 1
end
end

Resources