Rspec - config.before(:suite) 在 spec_helper 中不是 运行

Rspec - config.before(:suite) not running in spec_helper

我目前正在寻求在内存中设置一个可以在我的整个套件中使用的哈希 我希望执行以下操作

RSpec.configure do |config|
  config.before(:suite) { $user_tokens = initialize_my_stuff }
end

然而,当我进入 运行 我的套房时,我从我的一个规格中得到了一个错误: NoMethodError: undefined method 'each' for nil:NilClass

它正在尝试 运行 这个:

$user_tokens.each do |user,token|
  describe 'foo bar' do
    ...
  end
end

如果我注释掉此规范,before(:suite) 运行 将按预期显示。

有什么方法可以确保 before(:suite) 在 尝试对规格做任何事情之前阻止 运行s

情况如下:

config.before(:suite) { $user_tokens = initialize_my_stuff }

它将 运行 在套件 之前(毫不奇怪),但是...

$user_tokens.each do |user,token|
  describe 'foo bar' do
    ...
  end
end

..只是规范定义,发生在实际套件执行之前

换句话说:

  describe 'foo bar' do
    ...
  end

只是一堆保存起来稍后执行的块。而你的$user_tokens还没有初始化。

我建议在您的规范中使用 initialize_my_stuff,如下所示:

initialize_my_stuff.each do |user,token|
  describe 'foo bar' do
    ...
  end
end

或者,如果超级贵,记住它:

def user_tokens
  @user_tokens ||= initialize_my_stuff
end

并使用它

user_tokens.each do |user,token|
  describe 'foo bar' do
    ...
  end
end