Mocking chain of methods in rspec

15,974

I found I need to use receive_message_chain

So this worked for me.

allow(AuthorizeApiRequest).to receive_message_chain(:call, :result).and_return(user)
Share:
15,974
Decrypter
Author by

Decrypter

I have a strong passion for programming and a particular interest in web technologies. I love to experiment with interesting web technologies both server and client side.

Updated on June 22, 2022

Comments

  • Decrypter
    Decrypter almost 2 years

    There are a chain of methods which gets a user object. I am trying to mock the following to return a user in my Factory Girl

    @current_user = AuthorizeApiRequest.call(request.headers).result
    

    I can mock the object up until the call method but I'm stuck at mocking the result method

    allow(AuthorizeApiRequest).to receive(:call).and_return(:user)
    
  • jfc
    jfc about 5 years
    This works in some cases, but notice the "Warning" in the doc page: "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." They recommend using double or double_instance, as explained here: stackoverflow.com/a/51922393/2233856.