Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a simple global variable in an rspec test that can be accesed by helper functions

I cant figure out how to use a simple global variable in an rspec test. It seems like such a trivial feature but after much goggleing I havent been able to find a solution.

I want a variable that can be accessed/changed throughout the main spec file and from functions in helper spec files.

Here is what I have so far:

require_relative 'spec_helper.rb'
require_relative 'helpers.rb'
let(:concept0) { '' }

describe 'ICE Testing' do
    describe 'step1' do
    it "Populates suggestions correctly" do
         concept0 = "tg"
         selectConcept() #in helper file. Sets concept0 to "First Concept"
         puts concept0  #echos tg?? Should echo "First Concept"
    end
 end

.

 #helpers.rb
 def selectConcept
      concept0 = "First Concept"
 end

Can someone point out what I am missing or if using "let" is totally the wrong method?

like image 640
Tony Gutierrez Avatar asked Oct 03 '13 18:10

Tony Gutierrez


2 Answers

Consider using a global before hook with an instance variable: http://www.rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration

In your spec_helper.rb file:

RSpec.configure do |config|
  config.before(:example) { @concept0 = 'value' }
end

Then @concept0 will be set in your examples (my_example_spec.rb):

RSpec.describe MyExample do
  it { expect(@concept0).to eql('value') } # This code will pass
end
like image 50
Winston Kotzan Avatar answered Oct 14 '22 23:10

Winston Kotzan


It turns out the easiest way is to use a $ sign to indicate a global variable.

See Preserve variable in cucumber?

like image 37
Tony Gutierrez Avatar answered Oct 15 '22 01:10

Tony Gutierrez