Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec - as_null_object?

Tags:

ruby

rspec2

It's not clear to me what the purpose of as_null_object is and in what scenarios you would use it? According to the documentation on Relish:

Use the as_null_object method to ignore any messages that aren't explicitly set as stubs or message expectations.

Not registering with me.

like image 405
keruilin Avatar asked May 04 '12 03:05

keruilin


2 Answers

Use a null object when you don't care about the object's behavior or interaction, and don't want to explicitly stub everything out that's needed. Calling any method with any arguments on a null object will not result in a NoMethodError or ArgumentError. See also the Wikipedia entry on the Null Object Pattern.

like image 173
Andrew Marshall Avatar answered Sep 20 '22 15:09

Andrew Marshall


The RSpec Book explains this. I recommend you to read it.

... as_null object tells the mocked object to only listen for the messages we tell it to expect, and ignore any other messages.

So, suppose one of your examples has the following code:

...
my_object = mock("my_object" ).as_null_object
other_thing = OtherThing.new(my_object)
my_object.should_receive(:some_method).with("string parameter value")
...

If the initialization code for OtherThing sends other messages (executes other methods) to my_object that are not "some_method", this example will not listen to them, isolating the test to what you actually want to test here.

like image 33
Christian Avatar answered Sep 20 '22 15:09

Christian