Search code examples
rubyunit-testingrspec

RSpec mock a class with nested attributes


I'm very new to Ruby and RSpec and I'm having trouble trying to mock a chain of attributes inside of a class:

client.conversations.configuration.update(sid: user.sid)

I have already mocked the client like so:

let(:client) { class_double(Service::ClientFactory) }

However, this is what I've tried and failed using the receive method, which doesn't work.

  allow(client).to receive(conversations.configuration.update).and_return("123123123")

How can I do this correctly? Thank you!


Solution

  • You might want to use receive_message_chain:

    allow(client)
      .to receive_message_chain(:conversations, :configuration, update: "123123123")
    

    But please take a look at the section on that page too:

    Warning:

    Chains can be arbitrarily long, which makes it quite painless to violate the Law of Demeter in violent ways, so you should consider any use of receive_message_chain a code smell. [...]