RSpec 中的简单 instance_variable_set 不起作用,但为什么不呢?

Simple instance_variable_set in RSpec does not work, but why not?

在使用 RSpec:

测试 Ruby 应用程序时,我有点迷失在一项简单的任务中
class Script
  # content does not matter
  def initialize
  end

  def my_timezone_description(timeZoneId)
    @timeZonesCache[timeZoneId]
  end
end

规格:

  it 'gets the timezone description' do
    Script.instance_variable_set(:@timeZonesCache, {123 => '+01:00'} )
    expect(Script.new.my_timezone_description(123)).to eq '+01:00'
  end

Script.instance_variable_get(:@timeZonesCache) 返回正确的哈希值。

有人可以解释为什么这不起作用以及我如何让它起作用吗?

您需要在 Script 实例上调用 #instance_variable_set,而不是 class 本身:

  it 'gets the timezone description' do
    script = Script.new
    script.instance_variable_set(:@timeZonesCache, ({123 => '+01:00'}) )
    expect(script.my_timezone_description(123)).to eq '+01:00'
  end

否则你为 class 对象设置实例变量,而不是实例对象。

你现在所做的相当于

class Script
  @timeZonesCache = {123 => '+01:00'}
end