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)
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, 2022Comments
-
Decrypter almost 2 years
There are a chain of methods which gets a
user
object. I am trying to mock the following to return auser
in myFactory Girl
@current_user = AuthorizeApiRequest.call(request.headers).result
I can mock the object up until the
call
method but I'm stuck at mocking theresult
methodallow(AuthorizeApiRequest).to receive(:call).and_return(:user)
-
jfc about 5 yearsThis 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
ordouble_instance
, as explained here: stackoverflow.com/a/51922393/2233856.