How do you stub all methods of a particular mock instance
-
02-06-2021 - |
Question
I have a particular mock that is being handled by a third party. I just want to check that the same mock has been returned back.
However, the third party calls array methods and save methods that my test doesnt really care about. Is there a way to tell my mock that it expects/stub all methods to do with that particular mock instance?
eg.
user = mock(User)
user.stub_all
Thanks!
EDIT
More info about the problem:
Test:
it "creating an invitation should return invitation" do
invitation = mock_model(Invitation)
invitation.stub(:[]=)
invitation.stub(:save)
Invitation.stub(:create).and_return(invitation)
@user.create_invitation
@user.create_invitation.should == invitation
end
Code being tested:
def create_invitation
invitation = Invitation.create
self.invitations.push(invitation)
return invitation
end
I need to mock the following which are not directly related to what I am testing:
invitation.stub(:[]=)
invitation.stub(:save)
Solution
The answer is
user = mock(User).as_null_object
but in general this approach means your objects are too large and your tests aren't granular enough
OTHER TIPS
I came across this accidentally - but the 'blessed' way of doing this (now) is using the spy
method, which essentially is the same thing as above:
reference: https://thoughtbot.com/blog/a-closer-look-at-test-spies
You don't have to stub out any methods that the class implements already.