Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking chain of methods in rspec

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)
like image 345
Decrypter Avatar asked Nov 13 '16 08:11

Decrypter


People also ask

What is a mock in RSpec?

(Or a mock in general, because this isn’t a concept unique to RSpec.) A mock is an object used for testing. You use mocks to test the interaction between two objects. Instead of testing the output value, like in a regular expectation. You’re writing an API that flips images.

How do I create a double with RSpec?

Creating a double with RSpec is easy: A new double resembles a plain Ruby Object — it’s not very useful on its own. It is usually the first step before defining some fake methods on it. This is called method stubbing, and with RSpec 3 it is done using the allow () and receive () methods:

What is method stubbing in RSpec 3?

A new double resembles a plain Ruby Object — it’s not very useful on its own. It is usually the first step before defining some fake methods on it. This is called method stubbing, and with RSpec 3 it is done using the allow () and receive () methods:

How do you know if a method needs to be mock?

If the method under test returns a value & it has no side effects (creating files, making API requests, etc.) then you don’t need a mock. Just check for the return value. If the method is working with external objects & sending orders to them, then you can mock the interactions with these objects.


1 Answers

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)
like image 89
Decrypter Avatar answered Oct 12 '22 21:10

Decrypter