Thursday, June 9, 2016

[Linux/Unix] How to pass command line arguments to RSpec script?

RSpec doesn't allow you pass custom arguments in command line, however you can pass them as environment variable in Linux (doesn't work for windows)

Suppose you want to pass configuration file to the script as argument while running rspec, you can do this way:

CONFIG_FILE="example.yaml" rspec example_spec.rb

Access the environment variable in the script

describe "something" do  before(:each) do    config_file = ENV["CONFIG_FILE"]
  end
  it "does something that passes" do    expect(5).to eq(5)
  end
end
 
 

The test script should start with "RSpec.describe" or "describe"?

According to Rspec documentation, it is recommended to use the following syntax to write a test script. i.e. the Test script should start with "RSpec.describe":
 
#example_spec.rb
# 
RSpec.describe EvampleTest do  describe '#Group 1' do
    it 'test 1', :smoke => true do
    end
end

When you run the above example, it throws error uninitialized constant EampleTest (NameError), this happens because the class 'ExampleTest' is not defined. You have create a file with class 'ExampleTest' in lib folder like this
 
#lib/example.rb
class ExmpleTest
end
 
And include 'exmple.rb' in your script 
#example_spec.rb 
use 'example' 
 
RSpec.describe EvampleTest do  describe '#Group 1' do
    it 'test 1', :smoke => true do
    end 
end

However This is not mandatory, you can also write Rspec script without creating a dummy class. Just write your script by using "describe" instead of "RSpec.describe" as below

#example_spec.rb
# 
describe "Example Test" do  describe '#Group 1' do
    it 'test 1', :smoke => true do
    end
end


How to format the Rspec output? or write output on to a file?

Rspec supports various types of output formats like Html, Progress/Txt and Progress. You can use any one of them or all of them once

Add the following lines to your .rspec file:

--format progress 

--format documentation -o "output/result.log"
--format html -o "output/result.html"

--format specifies the type of output format and -o tag is used to write the output to a specified file

[Windows] How to resolve ANSI codes displayed in the Rspec output?


Today I ran into a problem while running Rspec script from the windows command line, instead of display the output in Progress format, it displayed some ANSI codes in the output as below:




The issues is with windows command prompt, it is not able to render the ANSI color codes, you can resolve this issue by removing --color tag or using --no-color tag