1

I am kind of lost in a simple task in testing a Ruby app using RSpec:

class Script
  # content does not matter
  def initialize
  end

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

Specs:

  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) gives me back the correct hash.

Can someone explain why this is not working and how I can get it to work?

1
  • 1
    Hint: instance_variable_set sets a variable on an instance. What instance are you calling it on? What instance are you reading the instance variable back from? Commented Nov 29, 2019 at 17:12

1 Answer 1

2

You need to call #instance_variable_set on Script instance, not on the class itself:

  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

Otherwise you set instance variable for the class object, not for the instance object.

What you do now is a equivalent of

class Script
  @timeZonesCache = {123 => '+01:00'}
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.