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

回眸只為那壹抹淺笑 提交于 2019-12-01 00:53:23

问题


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?


回答1:


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



回答2:


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

See Preserve variable in cucumber?



来源:https://stackoverflow.com/questions/19167031/how-to-define-a-simple-global-variable-in-an-rspec-test-that-can-be-accesed-by-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!