Rspec command line argument not supported? - ruby

My website will be tested in different languages and browser (Firefox, Chrome).
I use Ruby, watir-webdriver and rspec.
How do I write tests with Ruby, watir and rspec , that I can specify command line arguments ?
Example: rspec testfile.rb 1 2
1 => language finnland (load XML file)
2 => firefox
rspec gives me an error message for this example code:
argOne = ARGV[0].to_i
argTwo = ARGV[1].to_i
rspec can't process the command line argument?
Thank you for your help

According to this post on the ruby forum, you cannot pass argument to rspec, but you can pass variable from the command line via the environment variables
command line ( on Linux / bash )
LANG=1 BROWSER=2 rspec testFile.rb
command line ( on Windows )
set LANG=1
set BROWSER=2
rspec testFile.rb
in your testFile.rb
argOne = ENV["LANG"].to_i
argTwo = ENV["BROWSER"].to_i

Related

Ruby cmd line script executes code non-consecutively

I've built a ruby script that is supposed to run in the terminal.
$ ruby script.rb
I have some code specific to newer versions of ruby so I added a ruby version check towards the top of the page:
abort("You're using ruby #{RUBY_VERSION}. Please use version 2.1 or newer") if (RUBY_VERSION.to_f < 2.1)
I double checked the code line in irb and seems to work when changing the ruby version via RVM.
However, when I run the ruby script file under, say ruby 1.8.7, the script blows up with the following error:
$ ruby script.rb
script.rb:6: odd number list for Hash
option1: 'some options',
^
script.rb:6: syntax error, unexpected ':', expecting '}'
option1: 'some options',
^
script.rb:6: syntax error, unexpected ',', expecting $end
This would be expected behavior if I didn't have the version check on the top of the file.
Why doesn't the version check execute before the next lines of code? Is there a way to force execution of the ruby check before continuing with the rest of the code?
My full file is:
#!/usr/bin/env ruby
abort("You're using ruby #{RUBY_VERSION}. Please use version 2.1 or newer") if (RUBY_VERSION.to_f < 2.1)
options = {
option1: 'some options',
option2: 'some more options',
option3: 'other options'
}
That error is on the ruby parser. In ruby 1.8.7 hashes with symbols must be written with hashrockets { :option => 'some options'} because the shorthand { option: '' } was only introduced in ruby 1.9
To explain it better, ruby has to parse the whole file before executing anything on it. So your version check wont be executed because your file has invalid ruby 1.8 syntax.

Ruby gets method throws an exception when arguments are passed from the console

I have experienced some ODD behavior from the code below:
require 'CSV'
$DEBUG = ARGV.empty? ? false : ARGV[0] #Global debug flag.
class PhoneBook
#class code here etc etc
end
PhoneBook.start_dir = "file-io-samples/phonebooks/"
puts "Enter a phonebook!"
name = gets #This is the problem.
puts "Using #{name}.."
When I pass true to have $DEBUG set to true on execution I get an error from name = gets and I have no idea why. If I don't pass parameters via the command line everything works fine.
This is the error output:
C:\Pickaxe>ruby PhoneBook.rb
Enter a phonebook!
Hurrah! Works
Using Hurrah! Works
..
C:\Pickaxe>ruby PhoneBook.rb true
Enter a phonebook!
Exception `Errno::ENOENT' at PhoneBook.rb:62 - No such file or directory - true
PhoneBook.rb:62:in `gets': No such file or directory - true (Errno::ENOENT)
from PhoneBook.rb:62:in `gets'
from PhoneBook.rb:62:in `<main>'
C:\Pickaxe>
If I need to I can post the class definition, but I don't think it's part of the problem.
gets reads from stdin if no arguments are passed, and from the file that was passed as an argument otherwise. You are passing an argument true, ergo gets tries to read from a file named true, which apparently doesn't exist.
This is the very first sentence of the documentation of gets:
Returns (and assigns to $_) the next line from the list of files in ARGV (or $*)
This wouldn't cause a problem on *nix, but I expect Windows, or Ruby on Windows, isn't handling the additional command-line parameter the same way. On *nix, we can use -- between the script name and the parameter to tell the OS not to pass the parameter as a flag. In other words, Ruby wouldn't see true, your script would.
ruby some_script.rb -- options
But, in general, I think you're doing it wrong and recommend handling your command-line options in a standard way by using the OptionParser class:
require 'optparse'
OptionParser.new do |opt|
opt.on('-d', '--[no-]debug') { |o| $DEBUG = o }
end.parse!
puts $DEBUG
Running that several times on my Mac OS system, with different parameters, gives me:
$ ruby test.rb
false
$ ruby test.rb --no-debug
false
$ ruby test.rb -d
true
$ ruby test.rb --debug
true
You might still have to use -- to tell the OS and called app which parameters belong to what.

Ruby + Cucumber: How to execute cucumber in code?

I'd like to execute Cucumber features from within Ruby code.
Typically the cucumber binary installed with the gem is executed on the command line with one or more features specified.
However, I'd like to define logic that creates a dynamic feature execution flow. In other words, the program can work out which features should be executed.
Is it possible to instantiate Cucumber with specified feature files from Ruby code as opposed to the command line?
I discovered how from the mailing list and some API reading.
features="path/to/first.feature path/to/second.feature"
runtime = Cucumber::Runtime.new
runtime.load_programming_language('rb')
Cucumber::Cli::Main.new([features]).execute!(runtime)
If you want all features within your gem's features/ directory to be executed, pass an empty array to Main.new instead.
To convert this example command, with features and options specified:
cucumber features/first.feature features/second.feature -d -f Cucumber::Formatter::Custom
into Ruby code, it boils down to passing Cucumber an args array:
require 'cucumber'
# Method 1 - hardcoded features
args = %w(features/first.feature features/second.feature -d -f Cucumber::Formatter::Custom)
# Method 2 - dynamic features
features = 'features/first.feature features/second.feature'
args = features.split.concat %w(-d -f Cucumber::Formatter::Custom)
# Run cucumber
begin
Cucumber::Cli::Main.new(args).execute!
rescue SystemExit
puts "Cucumber calls #kernel.exit(), killing your script unless you rescue"
end
Tested using Ruby 2.0.0p598 and Cucumber 1.3.17

RSpec and Testing Command Line Args Passed to Script

I'm some rspec tests for a command line ruby based application. I'm trying to build my test suite allow for testing of missing command line parameters. Specifically, I'd like to stub out what ARGV[0]..ARGV[N] would appear to the application. I've seen similar posts mention ENV.stub; however, I don't see how I can simulate "nameless" args and a given order.
Any help would be appreciated. Thanks.
I simply did this in my test case located in spec:
it "does something" do
arg = "/tmp"
exe = File.expand_path('../bin/site_checker', File.dirname(__FILE__))
stdin, stdout, stderr = Open3.popen3("#{exe} -Ilib #{arg}")
stdout.readlines.should be_empty
end

Unexpected token error with Ruby

Attempting to execute the basic.rb example for HTTParty. Running into an interesting error. Executing this under 1.8.7 on my Mac (10.7.2). When I run the example (see code below), I get this error:
$ ./HTTPartyTest.rb
./HTTPartyTest.rb: line 1: syntax error near unexpected token `('
./HTTPartyTest.rb: line 1: `dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))'
If I take line 1 and execute it via irb I get this result.
>> dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
=> "/Users/me/Workspaces/lib"
Not sure why this occurring. Any help is appreciated.
You probably need to add the correct hash-bang header or this will be executed using your shell instead:
#!/usr/bin/env ruby
# ... (Rest of program)
The alternative is to explicitly specify you want to run it with Ruby:
ruby ./HTTPartyTest.rb

Resources