19

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)
Decrypter
  • 2,784
  • 12
  • 38
  • 57
  • I have found this question http://stackoverflow.com/questions/8003445/rspec-stub-chains-with-arguments?rq=1 ,it may be useful for you – Srikanth Gurram Nov 14 '16 at 10:04

1 Answers1

35

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)
Lucas Moulin
  • 2,450
  • 3
  • 32
  • 41
Decrypter
  • 2,784
  • 12
  • 38
  • 57
  • 3
    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: https://stackoverflow.com/a/51922393/2233856. – jfc Mar 27 '19 at 14:44