Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec double expect/allow anything

I have a test double that I'd like to be able to receive any message.

I know I can expect the double to receive a certain message and return a value like so:

foo = double()
allow(foo).to receive(:bar) { "Foobar" }

I can also allow foo to receive any message using #as_null_object like:

foo = double()
foo.as_null_object

Is there any other syntax for this? Seems I should be able to do something like:

allow(foo).to receive(:anything)
like image 532
jordelver Avatar asked May 06 '14 23:05

jordelver


People also ask

How do you double in RSpec?

A Double is an object which can “stand in” for another object. You're probably wondering what that means exactly and why you'd need one. This is a simple class, it has one method list_student_names, which returns a comma delimited string of student names.

What is allow in RSpec?

Use the allow method with the receive matcher on a test double or a real. object to tell the object to return a value (or values) in response to a given. message. Nothing happens if the message is never received.

How do I mock an instance variable in RSpec?

You can't mock an instance variable. You can only mock methods. One option is to define a method inside OneClass that wraps the another_member , and mock that method. However, you don't have to, there is a better way to write and test your code.

What is a partial double RSpec?

A partial test double is an extension of a real object in a system that is instrumented with. test-double like behaviour in the context of a test. This technique is very common in Ruby. because we often see class objects acting as global namespaces for methods.


1 Answers

allow and expect methods can be used to stub methods/set expectations on particular method. Augmenting object with null object pattern is quite different, and thus uses different method call.

Please note that you should usually not use null object in area that is tested by particular test -- it is meant to imitate some part of the system that is side effect of tested code, which cannot be stubbed easily.

like image 94
samuil Avatar answered Oct 12 '22 13:10

samuil