问题描述
我不知道如何在 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.
这是我目前所拥有的:
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 钩子:http://www.rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration
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 测试中定义一个可由辅助函数访问的简单全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!