本文介绍了如何在rspec测试中定义可以由辅助函数访问的简单全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何在rspec测试中使用简单的全局变量。看来这是一个微不足道的功能,但是经过一番摸索之后,我仍然无法找到解决方案。

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

有人可以指出我所缺少的内容吗,或者使用 let是完全错误的方法吗?

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

推荐答案

考虑使用带有实例变量的全局before钩子:

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

在您的spec_helper.rb文件中:

In your spec_helper.rb file:

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

然后在您的示例中设置@ concept0(my_example_spec.rb):

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

这篇关于如何在rspec测试中定义可以由辅助函数访问的简单全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 13:17