Search code examples
ruby-on-railsrubyrspecrubygemsinstance-variables

How can I mock an instance variable returned from a Client in rspec


I have a service client that I call which returns a bunch of instance variables. I call this in a method which is called inside another method to return a response

I want my method to return a specific one like so

def returnsAlias
  model = ClientGem.find(id) #finds a bunch of instance variables by id
  model.alias #returns @alias
end

In my spec I have

allow(ClientGem).to receive(:find).and_return('Test Alias')

I'm not sure what to replace 'Test Alias' with. I tried @alias and using

@alias.instance_variable_set(:@alias, 'Test Alias')

But this returns this error

FrozenError:
   can't modify frozen NilClass

Solution

  • Simply stub out the object itself.

    model = instance_double(ClientGemReturnedKlass, alias: 'Test Alias')
    allow(ClientGem).to receive(:find).and_return(model)