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

后端 未结 3 1235
星月不相逢
星月不相逢 2021-01-11 18:05

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.

相关标签:
3条回答
  • 2021-01-11 18:48

    This is an old thread, but i had this question today. I just needed to define a long string to stub out a command that is in multiple files as:

    # in each spec file that needed it
    let(:date_check) do
       <<~PWSH.strip
       # lots of powershell code
       PWSH
    end
    
    # in any context in that file (or a shared context)
    before(:each) do
      stub_command(date_check).and_return(false)
    end
    

    Searched, Stack Overflow, etc, landed on this: Note the usage of the variable doesn't change at all! (Assumes all specs require 'spec_helper')

    # in spec_helper.rb
    def date_check 
      <<~PWSH.strip
      # lots of powershell code
      PWSH
    end
    
    # in any context in any spec file
    before(:each) do
      stub_command(date_check).and_return(false)
    end
    
    0 讨论(0)
  • 2021-01-11 18:51

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

    See Preserve variable in cucumber?

    0 讨论(0)
  • 2021-01-11 18:57

    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
    
    0 讨论(0)
提交回复
热议问题